axios-curlirize
axios-curlirize copied to clipboard
Incorrect headers
Hi,
Thanks for this module. I had a problem with the headers however. The default content-type isn't set correctly and the common header ('Accept': 'application/json, text/plain, */*') is not included. I followed the axios code in lib/defaults.js and lib/core/dispatchRequest.js to come up with my own simplified version:
import axios from 'axios';
import {isURLSearchParams, isObject, merge} from 'axios/lib/utils';
import qs from 'qs';
declare module 'axios' {
interface AxiosRequestConfig {
curlCommand?: string;
}
}
const filterKeys = new Set(['delete', 'get', 'head', 'post', 'put', 'patch', 'common']);
axios.interceptors.request.use(config => {
try {
const {method, url, params, data} = config;
let {headers = {}} = config;
let dataArg = '';
const setsContentType = Object.keys(headers).some(key => key.toUpperCase() === 'CONTENT-TYPE');
if(isURLSearchParams(data)) {
dataArg = ` --data '${data}'`;
if(!setsContentType)
headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
} else if(isObject(data)) {
dataArg = ` --data '${JSON.stringify(data)}'`;
if(!setsContentType)
headers['Content-Type'] = 'application/json;charset=utf-8';
}
headers = merge(
headers.common || {},
headers[method] || {},
headers,
);
config.curlCommand = `curl -X ${method.toUpperCase()} ${
Object.keys(headers).filter(key => !filterKeys.has(key))
.map(key => `-H "${key}:${headers[key]}"`)
.join(' ')
}${
dataArg
} "${url}${
params && Object.keys(params).length ?
`?${qs.stringify(params)}` :
''
}"`;
} catch (err) {
console.error(err);
} finally {
return config;
}
});
I confirm the content-type header is for sure wrong, json requests (axios default) are sent with form-urlencoded content-type.
I'm having the issue in v2.0/v1.3.7. I'll willing to help if someone can offer some guidence. :)
friendly ping @anthonygauthier :)
So I know this is an old issue, but I've been trying to reproduce this locally without any success. Any time I make a request to a service using axios the generated cURL command lists the right headers. One potential thing that might be happening is the presence of another interceptor modifying the headers field after curlirize already generated the command?
EDIT: My test cases actually catch all the headers and thus return a successful test run. That's what points me into thinking that other interceptors might be at play here.
it seems only happen with the non-get requests.
just made a simple repro: https://github.com/aladdin-add/repros/tree/repro-axios-curlirize-issue25
I also had the same issue in NestJS so I added the content-type during the module registration as follows and it correctly added the content-type header in the curl string.
...
import { HttpModule } from 'nestjs-http-promise';
...
HttpModule.register({
headers: {
'Content-Type': 'application/json',
},
}),
...