【发布时间】:2020-11-30 20:18:18
【问题描述】:
我正在尝试从 asp.net core 3.1 获取数据,因此我使用请求登录并获取 jwt 令牌。之后我想发送一个从 api 获取数据的请求,但它导致“预检请求”从源 'http://localhost:3000' 获取在 'https://localhost:44328/Address' 的访问已被阻止CORS 策略:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。 apiAddress.js:24 GET https://localhost:44328/Address net::ERR_FAILED",我使用 Visual Studio localhost 作为 api 服务器并配置启动如下:
//in ConfigureServices
services.AddCors(options =>
{
options.AddPolicy(name: AllowedOrigins,
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(hostName => true);
});
});
//in configure
app.UseCors(AllowedOrigins);
我的 fetch 请求在 reactjs 中如下所示:
const response = await fetch(url, {
'method': 'GET',
'mode': 'cors',
'credentials': 'include',
'headers': {
'Content-Type': 'application/json; charset=utf-8;',
//'Content-Type':'application/x-www-form-urlencoded',
'Authorization':`bearer ${token}`
}
});
最后我的控制器如下所示:
[ApiController, EnableCors("AllowedOrigins"), Authorize, Route("[controller]")]
public class AddressController : ControllerBase
出了什么问题,我必须提到没有 [Authorize] 属性的其他操作可以正常工作,但是带有它的操作不起作用?! 有人提到我应该在 iis 中启用选项,但没有解释如何?
【问题讨论】:
-
你的网址在
package.json的代理中,还是你把它写成一个字符串在ajax帖子里? -
'Authorization':bearer ${token}`` 这会触发 CORS 预检。我们可以在不触发 CORS 的情况下使用的标头和值非常具体。(Authorization不是其中之一) -
我把它写成变量中的字符串
-
那我该怎么办
标签: reactjs asp.net-core cors preflight