首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >CORS在使用Axios向节点服务器发送请求时发出

CORS在使用Axios向节点服务器发送请求时发出
EN

Stack Overflow用户
提问于 2020-07-22 18:30:27
回答 1查看 769关注 0票数 1

我偶然发现了一个问题,也许有人能帮上忙。目前,我已经通过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'.

我读过之前关于这个问题的堆栈溢出帖子,但是没有一个能解决我的问题。

我尝试过在请求的标题中设置访问-控制-允许-原产地,但这没有帮助。

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

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

我发送请求的代码如下所示,也许它可以帮助您解决查询。

代码语言:javascript
运行
复制
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;```
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-22 18:40:09

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

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

要做到这一点,只需在您的adonis服务器目录中。

directory.

  • Find

  • 转到配置

  • cors.js,并将来源从false更改为true

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63040932

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档