首页 > 解决方案 > 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
            }
        })

任何帮助都将不胜感激。我试过的:

标签: httpcorshttp-headersaxios

解决方案


您很困惑,因为状态为 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 代码的地方。


推荐阅读