首页 > 解决方案 > 如何将此 curl 命令转换为 JavaScript 的 fetch

问题描述

我有以下 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 命令有什么区别?

标签: javascriptcurlfetch

解决方案


我相信你的目标如下。

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

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

在这种情况下,下面的脚本怎么样?使用时FormDataContent-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'

推荐阅读