【问题标题】:React JS get errors in XMLHttpRequest with AxiosReact JS 使用 Axios 在 XMLHttpRequest 中获取错误
【发布时间】:2018-06-03 06:29:47
【问题描述】:

我正在为 FRONT-END 使用 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的控制台日志

【问题讨论】:

  • 这是一个 CORS(跨源)问题。类似的问题在这里:stackoverflow.com/questions/35164116/…此reddit线程中的其他故障排除:reddit.com/r/reactjs/comments/7kfqwi/…
  • 服务器应该支持 CORS 请求。如果您有权访问您的服务器,则应将其配置为发送这些标头。只是谷歌cors阅读它。如果你使用 node.js 和 express,你可以看看 cors 中间件。
  • 不,我正在使用 laravel,我正在使用 axios 发送标头来解决 CORS 问题@GreggB
  • @coockoo 我在 AXIOS 中使用标头!
  • 你加了吗:withCredentials: true

标签: javascript reactjs


【解决方案1】:

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

更多详情,请查看this answer

【讨论】:

    猜你喜欢
    • 2020-08-21
    • 2020-04-27
    • 2017-12-29
    • 2021-09-29
    • 2021-05-19
    • 2022-09-15
    • 2022-11-12
    • 2017-11-27
    • 2017-07-18
    相关资源
    最近更新 更多