【发布时间】:2020-09-03 08:52:28
【问题描述】:
我正在尝试通过 fetch 方法将数据从我的 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)
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
我总是收到错误“POST http://127.0.0.1:8000/something/ net::ERR_ABORTED 415 (Unsupported Media Type)”,响应如下所示:“Response {type: "opaque", url: "", redirected: false, status :0,好的:假,...}”。 我的状态只包含空字符串(用户名:'',密码:'' 等)
我还尝试使用 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
你有解决这个问题的想法吗?
【问题讨论】:
标签: django reactjs axios fetch rest