使用 Javascript 获取 API 时动态更新 content-type header
Dynamically update content-type header when using Javascript Fetch API
我正在尝试使用 JavaScript Fetch API 发送一个 http POST 请求。到目前为止我得到的看起来像这样(以 TypeScript 表示法):
const fetchHeaders = new Headers();
fetchHeaders.append("Content-Type", "multipart/form-data; boundary=???");
const fetchOptions: RequestInit = {
method: "Post",
body: this.file,
headers: fetchHeaders
}
await fetch("uri", fetchOptions);
假设 this.file
是 .xls
或 .xlsx
Excel 使用 <input type="file">
上传的文件,我如何填充 boundary=
部分 Content-Type
header 在调用 fetch 时动态?
在 POSTMAN 中执行相同的操作时,边界会自动设置,但我不知道如何设置。
我找到了核心问题 - 将文件本身作为正文传递。我就是这样解决的:
const formData = new FormData();
formData.append("file", this.file, this.file.name);
const fetchOptions: RequestInit = {
method: "Post",
body: formData
}
我正在尝试使用 JavaScript Fetch API 发送一个 http POST 请求。到目前为止我得到的看起来像这样(以 TypeScript 表示法):
const fetchHeaders = new Headers();
fetchHeaders.append("Content-Type", "multipart/form-data; boundary=???");
const fetchOptions: RequestInit = {
method: "Post",
body: this.file,
headers: fetchHeaders
}
await fetch("uri", fetchOptions);
假设 this.file
是 .xls
或 .xlsx
Excel 使用 <input type="file">
上传的文件,我如何填充 boundary=
部分 Content-Type
header 在调用 fetch 时动态?
在 POSTMAN 中执行相同的操作时,边界会自动设置,但我不知道如何设置。
我找到了核心问题 - 将文件本身作为正文传递。我就是这样解决的:
const formData = new FormData();
formData.append("file", this.file, this.file.name);
const fetchOptions: RequestInit = {
method: "Post",
body: formData
}