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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With