React JS使用Axios时出现XMLHttpRequest错误

3

我正在使用REACT-JS框架进行前端开发:

下面是我在REDUX-REACT中的调用操作:

export function UserLogin(values) {
    var headers = {
        'Access-Control-Allow-Origin': '*',        
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }

    const request = axios.post('http://localhost:8000/login', headers,  values).then(function(response){
        /*() => {callback();}*/
        console.log(response);
    })
    .catch((error) => {
        // Error
        if (error.response) {
            console.log(error.response.data);

        } 
        else if (error.request) {
            // The request was made but no response was received
            // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
            // http.ClientRequest in node.js
            console.log(error.request);
        } 
        else {
            // Something happened in setting up the request that triggered an Error
            console.log('Error', error.message);
        }
    });
    return {
        type: LOGIN_REQUEST_SUCCESS,
        payload: request
    };
}

为了测试目的,我从其他localhost:8000获取答案。

我遇到了以下错误:

无法加载http://localhost:8000/login:预检请求的响应未能通过访问控制检查:所请求的资源上不存在 'Access-Control-Allow-Origin' 头。因此,不允许从源头 'http://localhost:3000' 访问它。

以及error.request的控制台日志。


1
这是一个CORS(跨域)问题。类似的问题在这里:https://dev59.com/FFsW5IYBdhLWcg3wSFnX 在这个Reddit帖子中有更多的故障排除:https://www.reddit.com/r/reactjs/comments/7kfqwi/using_reactjs_axios_how_do_you_bypass_cors_when/ - Gregg B
不,我正在使用Laravel,并使用Axios发送标头来解决CORS问题@GreggB - user8574331
@coockoo 我正在使用 AXIOS 中的 headers! - user8574331
@OlympikeSoft 是的,当你从前端发送请求时,你需要添加头部信息。同时,你也需要在后端响应中添加CORS头部信息。 - coockoo
@coockoo 有任何例子吗? - user8574331
显示剩余3条评论
1个回答

0

你应该在服务器的响应头中设置'Access-Control-Allow-Origin': '*',

更多细节请查看this answer


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接