我有以下 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/