使用 Axios 向节点服务器发送请求时出现 CORS 问题

CORS issue while sending request to Node Server using Axios

我偶然发现了一个问题,也许有人可以提供帮助。目前我已经在 React 项目中通过 npm 安装了 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'.

我之前阅读过有关此问题的堆栈溢出 post,但其中 none 解决了我的问题。

我已经尝试在请求的 header 中设置 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;```


 

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

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

为此,只需在您的 adonis 服务器目录中即可

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

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

您可以在 https://adonisjs.com/docs/4.1/cors

上阅读更多内容