如何将 *any* cURL 或 node-fetch 请求转换为 Axios 请求?

时间:2021-02-19 16:17:04

标签: javascript node.js google-chrome curl axios

我希望能够从 Chrome 开发者工具中的“网络”选项卡复制任何 HTTP 请求,并从 node.js 代码中将其作为 Axios 请求重新发送。 (尝试过 node-fetch 但发现 Axios 在几个重要方面更好)。但是,Chrome 仅具有以下复制请求的选项:Copy as Powershell、Copy as fetch、Copy as node.js fetch、Copy as cURL (cmd)、Copy as cURL (bash)。它不包括 Axios 选项。

遇到了几个可以转换 cURL 请求的在线工具:

  • https://curl.trillworks.com/ <== 从带有 Ansible、Browser (fetch)、Dart、Elixir、Go、JSON、Node.js (fetch)、Node.js (request)、MATLAB 选项的 cURL 转换、PHP、Python、R、Rust 或 Strest
  • https://onlinedevtools.in/curl <== 从带有上述选项子集的 cURL 转换:Go、JSON、Node.js、PHP、Python、R、Rust 或 Strest

但不幸的是,这些都没有适用于 Axios 的选项。我也找不到可以进行转换的 npm 包。它需要是可重复的,所以不确定最好的选择是什么,但它不能只是手动转换 - 感谢您提供任何建议。

2 个答案:

答案 0 :(得分:1)

正如你所说:

<块引用>

需要想办法做到这一点,无论是npm包,Chrome 扩展、在线工具甚至手工编写的 node.js 代码

我使用 curlconverter 编写了一个代码(它甚至是您用作示例的链接后面的一个包),可以帮助您。

它使用 toJsonString 方法首先将 cURL 字符串转换为 JSON,然后进行大量“解析”以创建一个漂亮且有用的 Axios 选项数组。从 cURL 翻译的“解析”:

  • 网址
  • 方法
  • 标题
  • 饼干
  • 数据(application/x-www-form-urlencodedmultipart/form-dataapplication/json)。

如果您需要其他东西,您可以使用代码作为基础并根据您的需要进行更改。

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;
}

因为它返回一个Axios,你可以正常使用它:

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);
})

答案 1 :(得分:1)

您可以使用 postman,并且可以将 cURL 转换为多种语言。

  1. 导入 cURL 命令 enter image description here enter image description here enter image description here

  2. 打开请求的代码面板 enter image description here

  3. 您可以在此处选择要转换的任何语言。 enter image description here