简体   繁体   English

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

[英]CORS issue while sending request to Node Server using Axios

I am stumbled upon a problem, perhaps some one can help.我偶然发现了一个问题,也许有人可以提供帮助。 Currently i have installed axios via npm in react project and while sending a request to node backend i am getting the following error目前我已经通过 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'.

I have read earlier stack overflow post on this concern but none of them solve my problem.我已经阅读了关于这个问题的早期堆栈溢出帖子,但没有一个能解决我的问题。

i have tried to set Access-Control-Allow-Origin in the header of request but it did not help.我试图在请求的 header 中设置 Access-Control-Allow-Origin,但它没有帮助。

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

I am using Adonis.js Framework for my backend, I am wondering if some on can help me out.我正在为我的后端使用 Adonis.js 框架,我想知道是否有一些可以帮助我。

My code for sending request is as follows,perhaps it can help you in solving the query.我发送请求的代码如下,也许它可以帮助您解决查询。


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;```


 

Cross-Origin Resource Sharing (CORS) is a way to allow incoming HTTP requests from different domains.跨域资源共享 (CORS) 是一种允许来自不同域的传入 HTTP 请求的方法。 It is very common in AJAX applications where the browser blocks all cross-domain requests if the server does not authorize them.在 AJAX 应用程序中很常见,如果服务器未授权,浏览器会阻止所有跨域请求。 So to solve your query, your server should enable the cross origin requests, not the client.因此,要解决您的查询,您的服务器应该启用跨源请求,而不是客户端。

Adonis.js give built in feature to turn the CORS on and off,turning it on will let your server start accepting requests from cross origins. Adonis.js 提供内置功能来打开和关闭 CORS,打开它将使您的服务器开始接受来自跨源的请求。

To do so, simply in your adonis server directory为此,只需在您的 adonis 服务器目录中

  1. Go to your config directory. Go 到您的配置目录。
  2. Find cors.js and change origin from false to true找到 cors.js 并将 origin 从 false 更改为 true

Your server should know start accepting request from cross origins.您的服务器应该知道开始接受来自跨源的请求。

You can read more here at https://adonisjs.com/docs/4.1/cors您可以在https://adonisjs.com/docs/4.1/cors阅读更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM