【发布时间】:2018-10-23 23:01:33
【问题描述】:
我使用 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”)。
但是它包含在选项请求中!
当我在 Axios 请求标头中添加 'Access-Control-Allow-Origin': '*' 时,警告消失了,但浏览器在 Options 请求成功后不会触发 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 块 //仍然没有成功
- Options 和/或 Post 请求返回状态码 204 //没有区别
【问题讨论】:
标签: http cors http-headers axios