在我的React应用程序中获取api数据时如何解决CORS错误? [英] How to fix CORS error when fetching api data in my React application?

查看:692
本文介绍了在我的React应用程序中获取api数据时如何解决CORS错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近将带有Redux(和KendoUI React)项目的ASp.NET CORE React上传到了我的Azure托管平台,现在,我无法访问从API提取的任何数据。我看了看控制台,看到了一条错误消息:

I recently uploaded my ASp.NET CORE React with Redux (and KendoUI React) project to my Azure hosting platform and now, I cannot access any data that is fetched from the API. I looked at the console and saw an error message of:


访问地址为' https://login.microsoftonline.com/xxx-xxx-xxx-xxx-xxx/oauth2/authorize?client_id=xxx-xxx-xxx-xxx-xxx&redirect_uri=https%3A%2F%2Fmywebsite.azurewebsites .net%2Fsignin-oidc& response_type = id_token& scope = openid%20profile& response_mode = form_post&nonce = xxx.xxxstate = xxx-xxx-xxx-xxx-xxxxxx& x-client-SKU = ID_NET& x-client-ver = 2.1.4.0 (从 https重定向:// mywe bsite.azurewebsites.net/api/MyData/GetMyData?page=1&pageSize=20 '),来自来源 https://mywebsite.azurewebsites.net 已被CORS政策阻止:所请求的资源上没有 Access-Control-Allow-Origin标头。如果不透明的响应满足您的需求,请将请求的模式设置为 no-cors,以在禁用CORS的情况下获取资源。

Access to fetch at 'https://login.microsoftonline.com/xxx-xxx-xxx-xxx-xxx/oauth2/authorize?client_id=xxx-xxx-xxx-xxx-xxx&redirect_uri=https%3A%2F%2Fmywebsite.azurewebsites.net%2Fsignin-oidc&response_type=id_token&scope=openid%20profile&response_mode=form_post&nonce=xxx.xxxstate=xxx-xxx-xxx-xxx-xxxxxx&x-client-SKU=ID_NET&x-client-ver=2.1.4.0' (redirected from 'https://mywebsite.azurewebsites.net/api/MyData/GetMyData?page=1&pageSize=20') from origin 'https://mywebsite.azurewebsites.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I通过搜索错误消息对问题进行了调查,我发现了几篇文章,但对于在最佳实践中也是安全的React应用程序中的确切操作并没有具体说明。

I investigated the problem by searching the error message, I found a few posts but nothing concrete on exactly what to do in a react application that is best practice and also secure.

我在提取中添加了 Access-Control-Allow-Origin:* 的标头,但没有工作。我发现的另一种方法是使用代理,但该示例仅支持本地开发环境。

I added a header of Access-Control-Allow-Origin: * to my fetch but it didn't work. The other method I found was to use a proxy but the example was only supporting a local development environment.

在这里是我的提取内容,您可以看到我添加了 Access-Control-Allow-Origin 到标题:

Here is my fetch where you can see I added the Access-Control-Allow-Origin to the headers:

fetchData(dataState) {
    const queryStr = `${toDataSourceRequestString(dataState)}`;
    const hasGroups = dataState.group && dataState.group.length;
    const base_url = 'api/MyData/GetMyData';
    const init = { method: 'GET', accept: 'application/json', headers: "Access-Control-Allow-Origin: *" };

    fetch(`${base_url}?${queryStr}`, init)
        .then(response => response.json())
        .then(({ Data, total }) => {
                this.setState({
                    result: hasGroups ? translateDataSourceResultGroups(Data) : Data,
                    total,
                    dataState
                });
            }).catch(function (error) {
                console.log('Error: \n', error);
            });
};

添加标头并没有改变,错误仍然存​​在。我想确保正确执行此操作,有人可以帮助我解决此错误吗?

Adding the header changed nothing and the error persists. I want to make sure I do this correctly, can anyone help me fix this error?

推荐答案

Access-Control-Allow-Origin 是响应头。它只能由服务器设置。服务器确定是否接受跨站点请求,在这种情况下,服务器拒绝。

The Access-Control-Allow-Origin is a response header. It can only be set by the server. The server determines whether or not it accepts cross-site requests and in this case, the server says no. There's no way around it.

似乎您正在尝试访问Azure服务器,但它会重定向到Microsoft登录页面。确保发出请求时可以在没有重定向的情况下访问服务器。还要确保您的JavaScript代码在同一域上运行(我认为是这样),否则请在Web服务器上配置CORS: https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-2.2

It seems you are trying to reach your Azure server but it redirects to the Microsoft login page. Make sure you can access the server without a redirect when making a request. Also make sure your JavaScript code is running on the same domain (I assume it is), otherwise configure CORS on the web server: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2

这篇关于在我的React应用程序中获取api数据时如何解决CORS错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆