简体   繁体   中英

Fetch API is returning 415 (Unsupported Media Type)

I would like to replace the axios package with the fetch api (or unfetch) but for some reason, fetch doesn't work for me. Axios is working just fine, so I replaced it with fetch but that is returning 415 (Unsupported Media Type) . I use it to upload a file to the server with a POST request. Maybe I am missing something in the fetch setup?

FormData

const upload = file.length > 0 && file[0]
formData.append('file', upload, upload.name)

Axios (working)

const {
  data: { small, large },
} = await axios({
  method: 'POST',
  url: `${API_URL}/upload/avatar`,
  data: formData,
  headers: {
    'Content-Type': 'multipart/form-data',
    Authorization: `Bearer ${getTokenFromCookie()}`,
  },
})

Fetch (not working)


const { data: { small, large } } = await fetch(`${API_URL}/upload/avatar`, {
  method: 'POST',
  body: formData,
  headers: {
    'Content-Type': 'multipart/form-data',
    Authorization: `Bearer ${getTokenFromCookie()}`,
  },
})

I think you're missing an 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, *.*',
  },
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM