http - Cors Post 请求上的 Axios 网络错误,状态码为 200
问题描述
我使用 axios 与我自己的 API 进行通信(不是用 NodeJS 编写的)。
当我发布一个非简单请求时,axios 总是直接进入在控制台中显示网络错误的 catch 块,即使有 2 个成功的 Http 请求也是如此。
错误:网络错误堆栈跟踪:createError@ http://localhost:3000/static/js/bundle.js:1634:15 handleError@ http://localhost:3000/static/js/bundle.js:1170:14
还有一个关于缺少标题的 CORS 警告
跨域请求被阻止:同源策略不允许在 http://127.0.0.1:8080读取远程资源。(原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。
但是它包含在选项请求中!
当我添加'Access-Control-Allow-Origin': '*'
Axios 请求标头时,警告消失了,但浏览器在选项请求成功后不会触发 Post 请求。
为了完整起见,这里是发布请求标头。
编码:
postForm = () => {
axios.post("http://127.0.0.1:8080/",
myComplexObj, {
headers: {
//'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
timeout: 15000
}
).then(res => {
console.log(res);
alert('success');
})
.catch(function(error) {
//code always end up here
console.log(error);
/*Error: Network Error
Stack trace:
createError@http://localhost:3000/static/js/bundle.js:1634:15
handleError@http://localhost:3000/static/js/bundle.js:1170:14
*/
console.log(error.response); //undefined
console.log(error.response.data); //undefined
}
})
任何帮助都将不胜感激。我试过的:
- 取消超时//没有变化
- 删除 Catch 块//仍然没有成功
- 在选项和/或发布请求上返回状态代码 204 //没有区别
解决方案
您很困惑,因为状态为 200,但是,如果缺少 Access-Control-Allow-Origin 标头,浏览器将不允许您访问 CORS 请求的响应。
以下是一些解释 CORS 工作原理的精彩文章:
https://www.html5rocks.com/en/tutorials/cors/
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
无论如何,我认为您正在使用 Django。因此,您需要添加到 settings.py:
CORS_ORIGIN_WHITELIST = (
'localhost:8080',
'localhost'
)
或者任何你有 axios 代码的地方。
推荐阅读
- python - 运行 chrome headless 时 Selenium 不加载页面 - python - 警报或弹出错误
- firebase - GoogleCredentials 不起作用并使应用程序瘫痪
- c# - 类需要什么才能使属性网格显示其属性?
- android - 如何将两个网络请求响应合并为单个对象
- mysql - 从订单表中检索过去 7 天的订单历史记录
- java - 通过 Jsch 端口转发的 Java 套接字连接
- lotus-notes - LotusScript - 如何创建按钮以更改某些字段中的值并刷新表单?
- php - Strip 不允许从我们的服务器调用他们的 API,而是抛出异常
- azure - 没有功能且正在运行后台线程的 Azure Function App
- svelte - 如何在 Sapper 中创建带有可选参数的路由?