我最近将我的ASp.NET CORE React与Redux(和KendoUI React)项目上传到我的Azure托管平台,现在,我无法访问从API获取的任何数据。我看着控制台,看到一条错误信息:
从'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://mywebsite.azurewebsites.net/api/MyData/GetMyData?page=1&pageSize=20'(从'https://mywebsite.azurewebsites.net'重定向)的访问权限已被CORS策略阻止:请求的资源上没有'Access-Control-Allow-Origin'标头。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。
我通过搜索错误消息调查了这个问题,我找到了一些帖子,但没有具体说明在反应应用程序中应该做什么,这是最佳实践并且也是安全的。
我在我的fetch中添加了Access-Control-Allow-Origin: *
的标题,但它没有用。我发现的另一种方法是使用代理,但该示例仅支持本地开发环境。
这是我的fetch,你可以看到我在标题中添加了Access-Control-Allow-Origin
:
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);
});
};
添加标题没有任何改变,错误仍然存在。我想确保我正确地执行此操作,任何人都可以帮我修复此错误吗?
Access-Control-Allow-Origin
是一个响应标题。它只能由服务器设置。服务器确定它是否接受跨站点请求,在这种情况下,服务器拒绝。没有办法绕过它。
您似乎正在尝试访问Azure服务器,但它会重定向到Microsoft登录页面。确保在发出请求时无需重定向即可访问服务器。还要确保您的JavaScript代码在同一个域上运行(我假设它是),否则在Web服务器上配置CORS:https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2
使用https://cors-anywhere.herokuapp.com
将此附加到您的api
例如:https://cors-anywhere.herokuapp.com/user/list
这是一个公共代理,无法控制谁看到数据,不会使代理服务器过载。如果无法改变azure api,最好实现自己的代理。