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

Viewed 3791

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 come across a couple of online tools that will convert cURL requests:

  • https://curl.trillworks.com/ <== 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.

3 Answers

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

  1. Import a cURL command enter image description here enter image description here enter image description here

  2. Open Code panel for the request enter image description here

  3. Here you can select any of the languages you want to convert. enter image description here

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@example.com\",\"password\": \"123456\"}'"

let result = curlToAxios(curl)

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