anthonygauthier / axios-curlirize Goto Github PK
View Code? Open in Web Editor NEWaxios plugin converting requests to cURL commands, saving and logging them.
License: MIT License
axios plugin converting requests to cURL commands, saving and logging them.
License: MIT License
Hi,
I tried to use this in node app but it gives me an error
node_modules/axios-curlirize/src/curlirize.js:1
import { CurlHelper } from './lib/CurlHelper';
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:811:22)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:879:10)
at Module.load (internal/modules/cjs/loader.js:731:32)
at Function.Module._load (internal/modules/cjs/loader.js:644:12)
at Module.require (internal/modules/cjs/loader.js:771:19)
at require (internal/modules/cjs/helpers.js:68:18)
Not sure what's going on. Is is suppose to work only in js engine that supports es modules?
Getting error while importing axios-curlirize,
ts-node ver. 9.1.1, typescript ver. 4.2.4
[ERROR] 14:27:26 Error: Must use import to load ES Module: node_modules/axios-curlirize/src/main.js
require() of ES modules is not supported.
require() of node_modules/axios-curlirize/src/main.js from temp.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename main.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from node_modules/axios-curlirize/package.json.
[5/5] Building fresh packages...
error C:\FRONTEND\www\nuxt-dashboard\node_modules\axios-curlirize: Command failed.
Exit code: 1
Command: if [ -e ./node_modules/.bin/babel ]; then ./node_modules/.bin/babel ./src --experimental --source-maps-inline -d ./dist; fi
Arguments:
Directory: C:\FRONTEND\www\nuxt-dashboard\node_modules\axios-curlirize
Output:
���।�������� ������: -e.
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
Should the logger be an option so that user can use their‘s logger ?
Would be useful if ther would be a utility method exposed that translates an axios request without running it. So not intercepting the axios request, just doing the translation, and from the request passed in, not the normalised/extended version that the interceptor gets. Thanks a million, it's great to see if someone provides a solution to an issue one has - even without this extra feature I described.
A POST request with a FormData object having a file binary in it results in the following:
curl -X POST -H "Content-Type:application/x-www-form-urlencoded" -H "content-type:multipart/form-data; boundary=--------------------------465935617733580427703067" --data '{"_overheadLength":412,"_valueLength":10,"_valuesToMeasure":[{"_readableState":{"objectMode":false,"highWaterMark":65536,"buffer":{"head":null,"tail":null,"length":0},"length":0,"pipes":null,"pipesCount":0,"flowing":false,"ended":false,"endEmitted":false,"reading":false,"sync":true,"needReadable":false,"emittedReadable":false,"readableListening":false,"resumeScheduled":false,"paused":true,"emitClose":false,"autoDestroy":false,"destroyed":false,"defaultEncoding":"utf8","awaitDrain":0,"readingMore":false,"decoder":null,"encoding":null},"readable":true,"_events":{"error":[null,null]},"_eventsCount":3,"path":"/tmp/1555512197006-en-GB-2-hello-world.txt","fd":null,"flags":"r","mode":438,"end":null,"autoClose":true,"bytesRead":0,"closed":false}],"writable":false,"readable":true,"dataSize":0,"maxDataSize":2097152,"pauseStreams":true,"_released":false,"_streams":["----------------------------465935617733580427703067\r\nContent-Disposition: form-data; name="sourceLocale"\r\n\r\n","it-IT",null,"----------------------------465935617733580427703067\r\nContent-Disposition: form-data; name="targetLocale"\r\n\r\n","en-GB",null,"----------------------------465935617733580427703067\r\nContent-Disposition: form-data; name="documentContent"; filename="1555512197006-en-GB-2-hello-world.txt"\r\nContent-Type: text/plain\r\n\r\n",{"source":{"_readableState":{"objectMode":false,"highWaterMark":65536,"buffer":{"head":null,"tail":null,"length":0},"length":0,"pipes":null,"pipesCount":0,"flowing":false,"ended":false,"endEmitted":false,"reading":false,"sync":true,"needReadable":false,"emittedReadable":false,"readableListening":false,"resumeScheduled":false,"paused":true,"emitClose":false,"autoDestroy":false,"destroyed":false,"defaultEncoding":"utf8","awaitDrain":0,"readingMore":false,"decoder":null,"encoding":null},"readable":true,"_events":{"error":[null,null]},"_eventsCount":3,"path":"/tmp/1555512197006-en-GB-2-hello-world.txt","fd":null,"flags":"r","mode":438,"end":null,"autoClose":true,"bytesRead":0,"closed":false},"dataSize":0,"maxDataSize":null,"pauseStream":true,"_maxDataSizeExceeded":false,"_released":false,"_bufferedEvents":[{"0":"pause"}],"_events":{},"_eventsCount":1},null],"_currentStream":null,"_boundary":"--------------------------465935617733580427703067"}' http://localhost:8080/dummyservice
Would you consider using the -F 'param=value'
flag and the @
notation for file uploads?
Example:
curl -s 'https://localhost:8080' -F 'param=key' -F 'file=@"files/hello world.txt"'
Can we obfuscate the password in the curl request?
Was it intended for babel/cli, etc. to be included in the dependencies list?
Unless I missed it (or more likely don't understand why it's needed), I don't see where it's being used.
A POST without a body is not exactly the same as a POST with a '{}' body, right now empty bodies are omitted and the resulting curl doesn't have the --data property.
IT would be expected this would incorporate baseUrl from the axios constructor.
It will be nice to allow support typescript
The documentation should be updated to explain the "axios" parameter in "curlirize(axios)".
If you are using the syntax below:
const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
(copied from axios readme)
Then you would need to invoke curlirize using "curlirize(instance)" after creating the instance. Even invoking it on "axios" before creating the instance doesn't cause the hook to be inherited.
Lost of a bit of time to that gotcha.
When I do not set the content type, like this:
let resp = await axios.post(baseUrl + '/page/init', data, {
headers: {
'nuwa-wings': 'env=osim232-v',
}
})
The generated cURL code will be like:
curl -X POST -H "Accept:application/json, text/plain, */*" -H "Content-Type:undefined" -H "nuwa-wings:env=osim232-v" ...
The package.json is:
{
"dependencies": {
"axios": "^1.6.2",
"axios-curlirize": "^2.0.0",
// etc...
}
}
Great module. congrats.
It would be wonderful it could allow (extra feature) only to dump the curl command in case of error.
I have given the basic auth credentials inside the auth
property in the config
object of the axios but the credentials are not logging along with the curl command.
Pls help.
axios supports passing a URLSearchParams object as data, when you need a post with "application/x-www-form-urlencoded".
curlirize prints an empty data object in the console.
Axios automatically appends a querystring if { params }
are given as second argument.
Curlirize prints just the url part of the config but it's not what axios is really sending, sent querystring is lost in the given curl printed.
I am getting the error below
import { CurlHelper } from "./lib/CurlHelper.js";
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
"dependencies": {
"axios": "^0.18.0",
"axios-curlirize": "^1.3.5",
.....
Let me know if anything else needed
I was using this as a way to help with generating my documetation, but unfortunately it doesn't generate headers and when data is specified it prints --data 'undefined'
Here is the error I can see If my request produce an error in jest :
(node:32584) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
| property 'curlObject' -> object with constructor 'CurlHelper'
--- property 'request' closes the circle
at stringify (<anonymous>)
at writeChannelMessage (internal/child_process/serialization.js:117:20)
at process.target._send (internal/child_process.js:805:17)
at process.target.send (internal/child_process.js:703:19)
at reportSuccess (./node_modules/jest-worker/build/workers/processChild.js:67:11)
like
const curlirize= require('axios-curlirize')
it will cause an error.
I'm using it on Expo and I found that it does not add the -H
header values to the generated command.
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;
}
});
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/[email protected]/work/seed-association-service/node_modules/axios-curlirize/src/main.js
require() of ES modules is not supported.
require() of /Users/[email protected]/work/seed-association-service/node_modules/axios-curlirize/src/main.js from /Users/[email protected]/work/seed-association-service/dist/dao.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename main.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/[email protected]/work/seed-association-service/node_modules/axios-curlirize/package.json.
// dao.ts
import axios from 'axios';
...
import curlirize from 'axios-curlirize';
console.log(curlirize); // this line was suggested in a different ticket
// curlirize(axios); // using this instead didn't change the error
$ versions
Node v14.19.1
NPM 6.14.16
Yarn 1.22.18
OS:
ProductName: macOS
ProductVersion: 12.5.1
BuildVersion: 21G83
$ cat package.json | grep "axios"
"axios": "~0.27.2",
"axios-curlirize": "~2.0.0",
"@types/axios-curlirize": "~1.3.2",
when I try to include this I get:
Error: Can't resolve './dist/curlirize'
Steps to reproduce:
Actual behaviour: The CURL output from Axios is displayed twice for each request
Expected behaviour: The CURL output is displayed only once (per request) no matter how many times Axios is curlirized.
Thanks!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.