javascript - 如何将此curl命令转换为JavaScript的fetch

标签 javascript curl 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 命令和获取表达式/生成的 cURL 命令有什么区别?

最佳答案

我相信您的目标如下。

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

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

既然如此,下面的脚本怎么样?使用 FormData 时,Content-Type 会通过包含边界自动添加到请求 header 。

示例脚本:

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

引用:

添加:

关于您的以下评论,

are you aware of a way to convert the original cURL command into something that doesn't use the -F option?

在这种情况下,按如下方式手动创建请求正文怎么样?

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'

关于javascript - 如何将此curl命令转换为JavaScript的fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67829949/

相关文章:

javascript - Selenium - 运行 javascript

javascript - 此示例使用什么 javascript 对象模式?

javascript - 具有 fwd 和 bck 功能的纯 javascript 图片库

c++ - 指定 header 的 libcurl

php - 在curl中登录和注销?

php - 在 Mysqli 准备语句中返回一个数组

javascript - 在另一个组件中使用函数时出错

http - 强制 cURL 发送无效的 HTTP header

javascript - Backbone.Collection 触发 'reset' 但不是 'add'

vue.js - 在 vuejs 中使用 vuex (dispatch) 出现错误 422