Django POST net::ERR_中止415(不支持的媒体类型)
我正试图通过以下方法将React应用程序中的数据发布到Django REST API:Django POST net::ERR_中止415(不支持的媒体类型),django,reactjs,axios,fetch,restapi,Django,Reactjs,Axios,Fetch,Restapi,我正试图通过以下方法将React应用程序中的数据发布到Django REST API: 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)
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)
})
我总是收到一个错误“POST net::ERR_ABORTED 415(不支持的媒体类型)”,响应如下:“response{Type:“不透明”,url:,redirected:false,status:0,ok:false,…}”。
我的状态仅包含空字符串(用户名:“”、密码:“”等)
我还尝试使用axios发送GET请求,并在控制台中打印响应:
axios.get('http://127.0.0.1:8000/something/')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error)
})
但答案是:
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
您有什么办法来解决这个问题吗?由于CORS限制,您在GET请求中遇到了这个问题,CORS限制是一个默认的浏览器限制,它阻止从外部API获取数据。 您可以执行以下操作:
关于POST请求期间收到的错误415,这是因为标头不匹配,因为您使用了“no cors”作为模式,所以请求标头变得不可变,因此即使您将“Content Type”作为“application/json”传递,它也会作为“text/char”传递,因为会引发此不匹配415错误。你可以联系后端团队,要求他们将“内容类型”更改为“文本/字符”,这应该对你有用。有没有其他方法可以让我不用联系后端团队就可以做到这一点不幸的是,没有。这是前端的死胡同,实际上你在这里无能为力,这是一个拦截器,联系后端团队是唯一的出路。