首页 > 解决方案 > 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()}`,
  },
})

标签: javascriptaxiosfetch

解决方案


我认为您缺少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, *.*',
  },
})

推荐阅读