gpt4 book ai didi

javascript - 使用 `fetch` 或 `request` 发送多部分/表单数据的正确方法

转载 作者:行者123 更新时间:2023-11-30 11:10:04 25 4
gpt4 key购买 nike

这是我要发送到服务器的数据结构:

{
attachment: [File],
foo: String,
bar: String
}

如您所见,我正在尝试发送一组文件以及一些其他数据。为了存储所有这些数据,我使用了 JavaScript 官方 API 中提供的 FormData() 构造函数。我正在像这样填充 formData:

for (let i = 0; i < this.state.files.length; i++) {
let f = this.state.files[i];
this.formData.append('attachment', f, f.name);
}
this.formData.append('foo', this.state.foo);
this.formData.append('bar', this.state.bar);

旁注:使用 React,react-dropzone 进行文件上传。我现在正在尝试将此数据提交到服务器。我首先尝试像这样使用 Fetch API:

fetch(url, {
method: method,
body: data,
headers: {
...authHeader(authToken)
}
}

没有太多的成功。方法是 POSTauthHeader(authToken) 只是生成Authorization: Bearer ...。问题是我认为指定的 header 会被我的身份验证 header 覆盖。

所以我尝试使用 requestrequest-promise-native。我做了类似的事情:

rp({
url,
method,
headers: {
...authHeader(authToken)
},
formData: data
});

结果相似。使用授权 header 和来自 FormData 的文件数组发送此类数据的正确方法是什么?

最佳答案

这是获取对象中可用的选项

fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})

如果您需要向服务器发送一些自定义 header ,只需这样写:

headers: {
"My-Custom-Header": "Custom-Header-Value",
}

因为你想发送一个多部分形式的数据,你只需要像这样将数据添加到请求的主体中:

body: formData 

如果您的字段位于表单标签内,您可以像这样设置表单数据:

var formData = new FormData(document.querySelector("form"));

如果您使用的是 http 身份验证,则有不同的身份验证方案,供引用使用此链接 https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication

如果您使用的是基本授权,那么您应该使用如下内容:

headers: {
'Authorization': 'Basic '+btoa('username:password')
}

关于javascript - 使用 `fetch` 或 `request` 发送多部分/表单数据的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54064696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com