Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST net::ERR_ABORTED 415 (Unsupported Media Type)

I'm trying to POST data from my React app to Django REST API by fetch method like this:

fetch('http://127.0.0.1:8000/something/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  mode: 'no-cors',
  body: JSON.stringify(this.state)
})
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error)
  })

I always get an error "POST http://127.0.0.1:8000/something/ net::ERR_ABORTED 415 (Unsupported Media Type)" and the response looks like this: "Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}". My state contains only empty strings (username: '', password: '' etc.)

I've also tried to send a GET request using axios and print a response in a console:

axios.get('http://127.0.0.1:8000/something/')
.then(function(response) {
  console.log(response);
})
.catch(function(error) {
  console.log(error)
})

But the response is:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/something/' from origin 
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' 
header is present on the requested resource.

Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)

GET http://127.0.0.1:8000/something/ net::ERR_FAILED

Have you got any ideas to fix that problem?

like image 796
adn98 Avatar asked Oct 25 '25 07:10

adn98


1 Answers

You are getting this issue in the GET request due to CORS restriction, which is a default browser restriction that prevents fetching data from external APIs. You can do the following:

  1. If you are using Google Chrome, add this extension-https://chrome.google.com/webstore/detail/who-cors/hnlimanpjeeomjnpdglldcnpkppmndbp?hl=en-GB.
  2. Reload the browser tab(s).

Regarding the error 415 you are receiving during POST request, it is because of header mismatch, since you have used 'no-cors' as your mode, your request headers become immutable, thus even if you are passing 'Content-Type' as 'application/json', it gets passed as 'text/char', because of this mismatch 415 error is thrown. You can contact the backend team and ask them to change the 'Content-Type' as 'text/char', it should work for you.

like image 80
Shree Nandan Das Avatar answered Oct 26 '25 21:10

Shree Nandan Das