【问题标题】:CORS issue while sending request to Node Server using Axios使用 Axios 向节点服务器发送请求时出现 CORS 问题
【发布时间】:2020-07-22 18:30:27
【问题描述】:

我偶然发现了一个问题,也许有人可以提供帮助。目前我已经通过 npm 在 react 项目中安装了 axios,并且在向节点后端发送请求时出现以下错误

Access to XMLHttpRequest at 'http://mechanicapp.test:3333/api/manufacturer?pagination=true&perPage=3' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains the invalid value 'false'.

我已经阅读了关于这个问题的早期堆栈溢出帖子,但没有一个能解决我的问题。

我尝试在请求的标头中设置 Access-Control-Allow-Origin 但没有帮助。

w.Header().Set("Access-Control-Allow-Origin", "*")

我正在为我的后端使用 Adonis.js 框架,我想知道是否有人可以帮助我。

我发送请求的代码如下,或许可以帮助你解决查询。


function checkAuthTokenExclusion(arr, url) {
    return (arr.indexOf(url) != -1);
}

let responseFormat = {
    error: false,
    response: {},
}

/*exclusion array, add those url to this array for which you dont want to set token in header*/
var exclusion = ['user-login'];

const axiosRequest = () => {
    const defaultOptions = {
        baseURL: "http://mechanicapp.test:3333/api/",
        /*  method: 'get',*/
        headers: {
            'Content-Type': 'application/json',
        },
    };

    // Create instance
    let instance = axios.create(defaultOptions);

    // Set the AUTH token for any request
    instance.interceptors.request.use(function (config) {

        /*the token will be added to header for those url which are not found in the exclusion array*/
        if (!checkAuthTokenExclusion(exclusion, config.url)) {
            const token = localStorage.getItem('fixlo-access-token');
            config.headers.Authorization = token ? `Bearer ${token}` : '';
        }
        return config;
    });

    return instance;
};


async function makeRequest(requestType = 'get', url, data = {},optionalConfig = {}) {

    let requestObj = null;

    switch (requestType) {
        case 'get':

            /*sample params pass code for get requests*/

            /*
                axiosRequest().get('/', {
                    params: {
                        results: 1,
                        inc: 'name,email,picture'
                    }
            });*/

            requestObj = axiosRequest().get(url, data);
            break;

        case 'post':
            requestObj = axiosRequest().post(url, data,optionalConfig);
            break;

        case 'put':
            requestObj = axiosRequest().put(url, data,optionalConfig);
            break;

        case 'delete':
            requestObj = axiosRequest().delete(url, data);
            break;

        default:
            /*if no params matches in switch case*/
            requestObj = axiosRequest().get(url, data);

    }




   await requestObj.then(callResponse => {
        /*success*/
        responseFormat.response = callResponse.data;
    }).catch(error => {
        /*error*/
        responseFormat.error = true;
        responseFormat.response = error.response.data;
    });



    return responseFormat;

}


// export default axiosRequest();
export default makeRequest;```


 

【问题讨论】:

    标签: reactjs axios adonis.js


    【解决方案1】:

    跨域资源共享 (CORS) 是一种允许来自不同域的传入 HTTP 请求的方法。 这在 AJAX 应用程序中很常见,如果服务器未授权,浏览器会阻止所有跨域请求。 因此,要解决您的查询,您的服务器应该启用跨源请求,而不是客户端。

    Adonis.js 提供了打开和关闭 CORS 的内置功能,打开它将使您的服务器开始接受来自跨源的请求。

    要这样做,只需在您的 adonis 服务器目录中

    1. 转到您的配置目录。
    2. 找到 cors.js 并将 origin 从 false 更改为 true

    您的服务器应该知道开始接受来自跨域的请求。

    您可以在https://adonisjs.com/docs/4.1/cors阅读更多内容

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 1970-01-01
      • 2015-02-10
      • 2021-09-12
      • 2019-08-08
      • 2014-07-06
      • 2018-02-02
      • 2023-03-08
      • 2022-11-23
      相关资源
      最近更新 更多