Axios总是出于某种原因失败

时间:2017-06-19 17:59:00

标签: reactjs

      handleLoginClick(event) {

        var apiBaseUrl = "http://localhost:8000/api-token-auth/";
        var self = this;
        var payload={
            "email": "myusername",//this.state.username,
            "password": "mypassword"//this.state.password
        };
        axios.post(apiBaseUrl, payload)
            .then(function (response) {
                alert('success')
            })
            .catch(function (error) {
                alert('NO') .  // <----- always reaches here.
                console.log(error);
            });
    }

出于某种原因,此代码始终失败并提示“否”。我正在尝试的端点是有效的,并且可以使用curl中的那些参数访问。有什么想法有什么不对吗?

我确实:

import axios from 'axios';

控制台输出:

XMLHttpRequest cannot load http://localhost:8000/api-token-auth/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

1 个答案:

答案 0 :(得分:2)

由于Same-origin policy,JavaScript无法读取您的请求。为了允许跨域请求,您必须在服务器端启用Cross-Origin Resource Sharing (CORS)标头。 出于开发目的,您可以使用代理(自己,或a simple service like crossorigin.me)或Allow-Control-Allow-Origin: * Chrome Extension

要允许来自任何域的呼叫,您必须提供以下标头(* - 表示任何,但是,您可以在此处列出域名):

Access-Control-Allow-Origin: *

要在Django应用中启用CORS,请参阅django-cors-headersdjango-cors-middleware