【问题标题】:How to convert this curl command to JavaScript's fetch如何将此 curl 命令转换为 JavaScript 的 fetch
【发布时间】:2021-08-22 01:52:28
【问题描述】:

我有以下 cURL 命令:

// original curl
curl https://example.com \
  -F "id=id" \
  -F "secret=secret"

我认为可以用这个fetch表达式表示:

// fetch
const body = new FormData();
body.append('id', 'id');
body.append('secret', 'secret');

return fetch('https://example.com', {
  method: 'POST',
  mode: 'no-cors',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  body,
})

然后,将获取请求复制为 cURL 生成以下命令:

// generated curl
curl 'https://example.com' \
  -H 'content-type: multipart/form-data' \
  --data-raw $'------WebKitFormBoundaryH2Ve4S1AUbboJ21W\r\nContent-Disposition: form-data; name="id"\r\n\r\nid\r\n------WebKitFormBoundaryH2Ve4S1AUbboJ21W\r\nContent-Disposition: form-data; name="secret"\r\n\r\nsecret\r\n------WebKitFormBoundaryH2Ve4S1AUbboJ21W--\r\n' \
  --compressed

令我惊讶的是,当端点和表单值使用真实数据而不是占位符数据时,原始 curl 请求有效,但生成的 curl 请求无效(获取版本也无效)。

我有什么明显的遗漏吗?原始 cURL 命令和 fetch 表达式 / 生成 cURL 命令有什么区别?

【问题讨论】:

    标签: javascript curl fetch


    【解决方案1】:

    我相信你的目标如下。

    • 您想将以下 curl 命令转换为 Javascript 的 fetch

        curl https://example.com \
          -F "id=id" \
          -F "secret=secret"
      

    在这种情况下,下面的脚本怎么样?当使用FormData 时,Content-Type 通过包含边界自动添加到请求头中。

    示例脚本:

    const body = new FormData();
    body.append('id', 'id');
    body.append('secret', 'secret');
    return fetch('https://example.com', {
      method: 'POST',
      // mode: 'no-cors' // I thought that this might not be required to be used. But please check this for your actual situation.
      body
    });
    

    参考:

    补充:

    关于您的以下评论,

    您知道将原始 cURL 命令转换为不使用 -F 选项的方法吗?

    在这种情况下,如何手动创建请求正文如下?

    curl -H 'Content-Type: multipart/form-data; boundary=boundaryboundary' \
      -d $'--boundaryboundary\r\nContent-Disposition: form-data; name="id"\r\n\r\nid\r\n--boundaryboundary\r\nContent-Disposition: form-data; name="secret"\r\n\r\nsecret\r\n--boundaryboundary--\r\n' \
      'https://example.com'
    

    【讨论】:

    • 您的目标是正确的,省略 Content-Type 标头是个好主意,但不幸的是,获取查询仍然与 curl 命令不同。请注意,在我的情况下,我确实需要使用 mode: 'no-cors'
    • 就我而言,在 fetch 示例中,response.ok 始终为 false。但是当使用原始的curl 命令时,我得到了一个有效的 JSON 响应
    • @Raphael Rafatpanah 感谢您的回复。我带来的不便表示歉意。关于mode: 'no-cors',我明白了。关于but unfortunately the fetch query is still different than the curl command.,不幸的是,我无法理解。我为此道歉。那我能问一下still different的细节吗?当我测试上面修改后的脚本时,我可以确认它与 curl 相同。所以我想确认一下你现在的情况。作为一个测试,比如上面修改过的脚本,当你没有使用mode: 'no-cors'时,你会得到什么结果?
    • @Raphael Rafatpanah 感谢您的回复。从您的回复中,我可以了解您的情况。当我再次检查您的 curl 命令和修改后的 Javascript 时,我确认两个请求是相同的。所以,我想确认一下是否还有其他情况。关于convert the original cURL command into something that doesn't use the -F option,在这种情况下,我认为可以手动创建请求体。为此,我在答案中添加了示例 curl 命令。
    • 我认为不同之处在于mode: 'no-cors' 导致response.status 始终为0source
    猜你喜欢
    • 2016-10-24
    • 2021-10-08
    • 2017-10-21
    • 2012-05-10
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多