【问题标题】:How to convert *any* cURL or node-fetch request into an Axios request?如何将 *any* cURL 或 node-fetch 请求转换为 Axios 请求?
【发布时间】:2021-05-22 15:47:47
【问题描述】:

我希望能够从 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 请求的在线工具:

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

【问题讨论】:

  • 为什么 chrome 网络选项卡会推动您的开发工作?我建议您退后一步并解释为什么要“从网络选项卡复制 CURL”开始,以及为什么需要将其转换为 Axios 请求.. 这没有任何意义
  • @chrismillah 用户需要能够从 Chrome 复制请求(包含所有 HTTP 标头等)并将其粘贴到 UI 中 - 然后将其添加到数据库中并定期触发通过 Axios 进行屏幕抓取。

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


【解决方案1】:

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

  1. 导入 cURL 命令

  2. 为请求打开代码面板

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

【讨论】:

    【解决方案2】:

    如你所说:

    需要想办法做到这一点,不管是npm包,Chrome 扩展程序、在线工具甚至是手工制作的 node.js 代码

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

    它使用toJsonString 方法首先将 cURL 字符串转换为 JSON,然后进行大量“解析”以制作一个美观实用的 Axios 选项数组。 “解析”从 cURL 翻译而来:

    • 网址
    • 方法
    • 标题
    • Cookie
    • 数据(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);
    })
    

    【讨论】:

    • 还没有时间尝试这个,但从表面上看它看起来是一个很好的开始。猜猜理想情况下它将被制成generator,添加测试并作为拉取请求提交......如果你(或其他人?)可以做到这一点,保证赏金!
    • 嘿,这是一个好主意,我会看到更多关于这个包的信息,并尝试做出拉动。完成后我会更新
    • 我这周有点忙,如果有人有空,请随时做:)
    猜你喜欢
    • 2020-02-26
    • 2020-01-12
    • 2019-08-17
    • 2021-11-12
    • 2021-07-20
    • 2019-06-28
    • 2021-04-28
    • 2018-04-16
    • 2021-02-06
    相关资源
    最近更新 更多