[英]CORS No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]React .NET Enable CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource
一直在尝试将 React 前端与 .NET 框架后端集成,并且我经常遇到 CORS 错误。 我发送到服务器的请求适用于 Postman。 我从 Postman 中提取代码并将其放入我的反应应用程序(Fetch)中,我收到以下错误:
Access to fetch at 'http://localhost:33333/Token' from origin 'http://localhost:3000' 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.
但是,在我的 .NET 后端我添加了以下过滤器:
using System;
using System.Web.Mvc;
namespace TheFifth.Cors
{
public class AllowCrossSiteAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin",
"*");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers",
"*");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials",
"true");
base.OnActionExecuting(filterContext);
}
}
}
然后引用了我的 Controller 顶部的过滤器
[AllowCrossSite]
public class DA_Object
{
//some code
}
有谁知道为什么我的 .NET 后端或我的 React 前端阻止我通过不同的端口进行通信——即使它适用于 Postman?
额外细节
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("type", "x");
urlencoded.append("username", "x@x.com");
urlencoded.append("password", "x@");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("http://localhost:33333/api/Token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
在 ConfigureServices 方法中的 startup.cs 中,您应该有类似的内容,如果没有,请添加它:
services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicyName, builder =>
{
//App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.
builder
.AllowAnyOrigin()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
在你的 appsettings.json 添加http://0.0.0.0:80像这样:
"App": {
...
"CorsOrigins": "http://*.mycompany.com,http://0.0.0.0:80",
...}
另一种解决方案是在浏览器中添加 CORS 扩展并启用它,但不推荐
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.