我遇到以下错误:
Access to XMLHttpRequest at 'https://localhost:44355/Brand' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我已经尝试了here的解决方案,但没有一个对我有用-指向Chrome插件的链接似乎不起作用。我没有尝试在Chrome中禁用CORS,因为这并不是我要找的解决方案。
我正在从React中获取GET:
axios
.get<BrandResponse>(url, {
'headers': { 'Authorization': 'Bearer ' + me.props.session.credentials.accessToken } })
.then((response: AxiosResponse<BrandResponse>) ...
我的服务器是一个dotnet核心MVC应用程序。我的控制器如下所示:
[Authorize]
[ApiController]
[Route("[controller]")]
public class BrandController : BaseController
{
...
[HttpGet]
[ProducesResponseType(StatusCodes.Status202Accepted, Type = typeof(BrandResponse))]
public async Task<ActionResult> SearchLcationsAsync([FromQuery] QueryBrand query)
=> (await QueryAsync(query)).ToActionResult();
}
然后在Startup.cs中添加CORS标头:
app.Use((context, next) =>
{
context.Response.Headers["Access-Control-Allow-Origin"] = config["AllowedHosts"];
return next.Invoke();
});
"AllowedHosts"
是*
的地方。
有什么想法吗?
答案 0 :(得分:3)
(在此阶段)设置什么Access-Control-Allow-Origin
标头都没有关系。阅读错误消息:
它没有HTTP正常状态。
可能您正在使用401 Unauthorized
响应来响应预检OPTIONS请求。这是一个问题,因为预检请求的目的是要请求具有该凭证的GET请求。
您需要从服务器上的身份验证规则中排除OPTIONS请求。
答案 1 :(得分:1)
结果是我错过了在app.UseCors();
中调用startup.cs
的问题,并且在调用头中从Cognito设置了错误的API密钥。