【问题标题】:Axios network error on Cors Post request with status code 200Cors Post 请求上的 Axios 网络错误,状态码为 200
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-12
      • 2013-02-18
      • 2022-01-08
      • 2021-02-15
      • 2018-11-29
      • 1970-01-01
      • 2021-11-16
      • 2021-01-21
      相关资源
      最近更新 更多