Giesburts
Giesburts

Reputation: 7648

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()}`,
  },
})

Upvotes: 5

Views: 6090

Answers (1)

Clarity
Clarity

Reputation: 10873

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, *.*',
  },
})

Upvotes: 1

Related Questions