![](/img/trans.png)
[英]Angular 6 - Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header
[英]Response to preflight request doesn't pass access control check (Angular2)
我在Asp.net中调用REST Web API时遇到错误。
XMLHttpRequest无法加载http:// localhost:54859 / api / PostData 。 对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此不允许来源' http:// localhost:3000 '访问。
我使用Angular2作为前端。 在后端,我添加了以下代码以在WEB API中启用CORS。
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
一切都适用于Http get请求,但同样不适用于Http Post请求。
任何帮助都会很明显
提前致谢!
我通过在web.config中添加以下行来解决它。
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
</modules>
</system.webServer>
谢谢。
在Global.asax.cs中的Application_BeginRequest期间为预检请求添加Access-Control-Allow-Origin
标头为我工作。
Global.asax/Global.asax.cs
protected void Application_BeginRequest(Object sender, EventArgs e)
{
// Preflight request comes with HttpMethod OPTIONS
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
// The following line solves the error message
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
// If any http headers are shown in preflight error in browser console add them below
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
解决此问题后,应用程序在浏览器控制台上抛出了错误,即在预检响应中未提及某些标头。
将标题添加到预检响应的Access-Control-Allow-Headers
标头后,它就会得到解决。
protected void Application_BeginRequest(Object sender, EventArgs e)
{
// Preflight request comes with HttpMethod OPTIONS
// The following line solves the error message
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
// If any http headers are shown in preflight error in browser console add them below
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
上面的代码运行正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.