我想用 fetch api(或 unfetch)替换 axios 包,但出于某种原因,fetch 对我不起作用。 Axios 工作正常,所以我用 fetch 替换了它,但它返回了 415(不支持的媒体类型)
。我用它通过 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
header :
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, *.*',
},
})
关于javascript - Fetch API 返回 415(不支持的媒体类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57266477/