[Fix #3540] Handle iterator request bodies in convertN8nRequestToAxios (#3567)

* Fix issue with request body not being sent when using the new request helper
This commit is contained in:
कारतोफ्फेलस्क्रिप्ट™ 2022-08-15 10:42:00 +02:00 committed by GitHub
parent 3608d132c0
commit e3f0ee68b4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -677,6 +677,10 @@ async function proxyRequestToAxios(
});
}
function isIterator(obj: unknown): boolean {
return obj instanceof Object && Symbol.iterator in obj;
}
function convertN8nRequestToAxios(n8nRequest: IHttpRequestOptions): AxiosRequestConfig {
// Destructure properties with the same name first.
const { headers, method, timeout, auth, proxy, url } = n8nRequest;
@ -716,21 +720,17 @@ function convertN8nRequestToAxios(n8nRequest: IHttpRequestOptions): AxiosRequest
};
}
// if there is a body and it's empty (does not have properties),
// make sure not to send anything in it as some services fail when
// sending GET request with empty body.
if (n8nRequest.body && Object.keys(n8nRequest.body).length) {
axiosRequest.data = n8nRequest.body;
const { body } = n8nRequest;
if (body) {
// Let's add some useful header standards here.
const existingContentTypeHeaderKey = searchForHeader(axiosRequest.headers, 'content-type');
if (existingContentTypeHeaderKey === undefined) {
axiosRequest.headers = axiosRequest.headers || {};
// We are only setting content type headers if the user did
// not set it already manually. We're not overriding, even if it's wrong.
if (axiosRequest.data instanceof FormData) {
axiosRequest.headers = axiosRequest.headers || {};
if (body instanceof FormData) {
axiosRequest.headers['Content-Type'] = 'multipart/form-data';
} else if (axiosRequest.data instanceof URLSearchParams) {
axiosRequest.headers = axiosRequest.headers || {};
} else if (body instanceof URLSearchParams) {
axiosRequest.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
} else if (
@ -738,6 +738,12 @@ function convertN8nRequestToAxios(n8nRequest: IHttpRequestOptions): AxiosRequest
) {
axiosRequest.data = new URLSearchParams(n8nRequest.body as Record<string, string>);
}
// if there is a body and it's empty (does not have properties),
// make sure not to send anything in it as some services fail when
// sending GET request with empty body.
if (isIterator(body) || Object.keys(body).length > 0) {
axiosRequest.data = body;
}
}
if (n8nRequest.json) {