javascript - Fetch API 返回 415(不支持的媒体类型)
问题描述
我想用 fetch api(或 unfetch)替换 axios 包,但由于某种原因,fetch 对我不起作用。Axios 工作得很好,所以我用 fetch 替换了它,但它正在返回415 (Unsupported Media Type)
. 我使用它通过 POST 请求将文件上传到服务器。也许我在获取设置中遗漏了一些东西?
表单数据
const upload = file.length > 0 && file[0]
formData.append('file', upload, upload.name)
Axios(工作)
const {
data: { small, large },
} = await axios({
method: 'POST',
url: `${API_URL}/upload/avatar`,
data: formData,
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${getTokenFromCookie()}`,
},
})
获取(不工作)
const { data: { small, large } } = await fetch(`${API_URL}/upload/avatar`, {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${getTokenFromCookie()}`,
},
})
解决方案
我认为您缺少Accept
标题:
const { data: { small, large } } = await fetch(`${API_URL}/upload/avatar`, {
method: 'POST',
body: formData,
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': `Bearer ${getTokenFromCookie()}`,
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
},
})
推荐阅读
- python - 我无法在 http 上使用 oauth2 验证 CKAN 2.7.2
- .net - ThreadPool C# 的更好替代品?
- c++ - 尝试为 Intel 编译器切换 MSVC 并出现 LNK1243 错误
- jquery - jquery closest doesn't work
- visual-studio-code - VSCode pipenv 已激活问题
- asp.net-mvc - C# MVC - RazorEngine 电子邮件模板创建带有 URL 链接的按钮
- api - 将用户语音文本发送到 Alexa 技能 API 端点
- ember.js - 页面加载前的 ember js 错误
- azure - 根据电子邮件域自动将 Azure AD 中的帐户类型从来宾更改为成员
- blockchain - 如何在超级账本锯齿中查询特定资源的交易