最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert *any* cURL or node-fetch request into an Axios request? - Stack Overflow

programmeradmin3浏览0评论

I'd like to be able to copy any HTTP request from the Network tab in Chrome Developer Tools and resend it from within node.js code as an Axios request. (Have tried node-fetch but found Axios better in several important ways). However, Chrome only has the following options for copying requests: Copy as Powershell, Copy as fetch, Copy as node.js fetch, Copy as cURL (cmd), Copy as cURL (bash). It doesn't include an Axios option.

Have e across a couple of online tools that will convert cURL requests:

  • / <== converts from cURL with options for Ansible, Browser (fetch), Dart, Elixir, Go, JSON, Node.js (fetch), Node.js (request), MATLAB, PHP, Python, R, Rust or Strest
  • <== converts from cURL with a subset of the options above: Go, JSON, Node.js, PHP, Python, R, Rust or Strest

But unfortunately neither of these have an option for Axios. I also haven't been able to find an npm package that would do the conversion. It needs to be repeatable so not sure what the best option would be but it can't just be a manual conversion - grateful for any suggestions.

I'd like to be able to copy any HTTP request from the Network tab in Chrome Developer Tools and resend it from within node.js code as an Axios request. (Have tried node-fetch but found Axios better in several important ways). However, Chrome only has the following options for copying requests: Copy as Powershell, Copy as fetch, Copy as node.js fetch, Copy as cURL (cmd), Copy as cURL (bash). It doesn't include an Axios option.

Have e across a couple of online tools that will convert cURL requests:

  • https://curl.trillworks./ <== converts from cURL with options for Ansible, Browser (fetch), Dart, Elixir, Go, JSON, Node.js (fetch), Node.js (request), MATLAB, PHP, Python, R, Rust or Strest
  • https://onlinedevtools.in/curl <== converts from cURL with a subset of the options above: Go, JSON, Node.js, PHP, Python, R, Rust or Strest

But unfortunately neither of these have an option for Axios. I also haven't been able to find an npm package that would do the conversion. It needs to be repeatable so not sure what the best option would be but it can't just be a manual conversion - grateful for any suggestions.

Share Improve this question edited Feb 26, 2021 at 13:39 Steve Chambers asked Feb 19, 2021 at 16:17 Steve ChambersSteve Chambers 39.4k29 gold badges175 silver badges220 bronze badges 4
  • Why would chrome network tab be driving your development efforts? I would suggest you take a step back and explain why you are "copying CURL from network tab" to begin with, and why that needs to be translated to an Axios request.. this makes no sense – chrismillah Commented Feb 22, 2021 at 21:44
  • @chrismillah The user needs to be able to copy a request from Chrome (plete with all HTTP headers etc.) and paste it into the UI - it is then added to the database and will be fired periodically via Axios for screenscraping. – Steve Chambers Commented Feb 23, 2021 at 9:53
  • @SteveChambers next time open a feature request github./curlconverter/curlconverter/issues – user3064538 Commented Sep 7, 2022 at 6:45
  • Also, onlinedevtools.in/curl sends your curl mand to their server, so you should remove any sensitive data from your curl mand if you use it. – user3064538 Commented Sep 7, 2022 at 9:14
Add a ment  | 

3 Answers 3

Reset to default 12 +25

You can use postman and you can convert cURL to several languages.

  1. Import a cURL mand

  2. Open Code panel for the request

  3. Here you can select any of the languages you want to convert.

As you said:

Need to find a way to do this, whether it be a npm package, Chrome extension, online tool or even hand-crafted node.js code.

I've made a code using curlconverter (it is even one package behind one link that you used as example) that can help you.

It uses toJsonString method to first convert the cURL string to JSON and after that, a lot of "parses" to make a beautiful and useful Axios options array. The "parses" translate from the cURL:

  • URL
  • Method
  • Headers
  • Cookies
  • Data (application/x-www-form-urlencoded, multipart/form-data and application/json).

If you need something else, you can use the code as a base and change it for your needs.

const curlconverter = require('curlconverter');

function curlToAxios(curl){
  let parsedCurl = curlconverter.toJsonString(curl);
  parsedCurl = JSON.parse(parsedCurl)
  // For some reason, sometimes the URL returns with quotation marks at the beginning and the end
  const qm = ['%27', '\''];
  qm.forEach(element => {
    if (parsedCurl.raw_url.startsWith(element)) {
      // Removing last occurrence
      var pos = parsedCurl.raw_url.lastIndexOf(element);
      parsedCurl.raw_url = parsedCurl.raw_url.substring(0,pos) + parsedCurl.raw_url.substring(pos+element.length);
      // Removing first occurrence
      parsedCurl.raw_url = parsedCurl.raw_url.replace(element, '');
    }
  });
  let axiosObject;
  let axiosOptions = {
    url: parsedCurl.raw_url,
    method: parsedCurl.method,
  };
  if (parsedCurl.headers && Object.keys(parsedCurl.headers).length > 0) {
    axiosOptions.headers = parsedCurl.headers;
  }
  if (parsedCurl.cookies && Object.keys(parsedCurl.cookies).length > 0) {
    // Convert cookies to 'cookie1=a; cookie2=b;' format
    let cookies = '';
    Object.keys(parsedCurl.cookies).forEach(element => {
      cookies += encodeURI(element) + '=' + (parsedCurl.cookies[element] ? encodeURI(parsedCurl.cookies[element]) : '') + '; ';
    });
    if (!axiosOptions.headers) {
      axiosOptions.headers = {}
    }
    axiosOptions.headers.Cookie = cookies
  }
  if (parsedCurl.data && Object.keys(parsedCurl.data).length > 0) {
    let data;
    // Form data
    if(parsedCurl.headers && (parsedCurl.headers['Content-Type'].includes('application/x-www-form-urlencoded') || parsedCurl.headers['Content-Type'].includes('multipart/form-data')) ) {
      data = '';
      Object.keys(parsedCurl.data).forEach(element => {
        data += (data !== '' ? '&' : '') + encodeURI(element) + '=' + (parsedCurl.data[element] ? encodeURI(parsedCurl.data[element]) : '');
      });
    } else if(parsedCurl.headers && parsedCurl.headers['Content-Type'] === 'application/json') {
      // The data here is on first element key
      data = Object.keys(parsedCurl.data)[0]
      data = JSON.parse(data);
    }
    axiosOptions.data = data;
  }
  axiosObject = axios(axiosOptions);

  return axiosObject;
}

As it returns an Axios, you can use it normally:

let curl = "curl --request POST \
--url http://localhost:3000/api/v1/users/new \
--header 'Content-Type: application/json' \
--data '{\"email\": \"[email protected]\",\"password\": \"123456\"}'"

let result = curlToAxios(curl)

result
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
})

https://curlconverter./node-axios/ now supports converting curl to Axios.

发布评论

评论列表(0)

  1. 暂无评论