是的,我知道你在想什么 - 另一个 CORS 问题,但这次我被难住了。
首先,实际的错误信息:
XMLHttpRequest cannot load http://localhost/Foo.API/token. The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:5000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
我不确定凭据模式是“包含”是什么意思?
所以当我在 postman 中执行请求时,我遇到没有这样的错误:
但是当我通过我的 angularjs 网络应用程序访问相同的请求时,我被这个错误难住了。这是我的 angualrjs 请求/响应。正如您将看到的响应是 OK 200
,但我仍然收到 CORS 错误:
Fiddler 请求和响应:
下图演示了Web前端对API的请求和响应
因此,根据我在网上阅读的所有其他帖子,似乎我在做正确的事,这就是我无法理解错误的原因。最后,这是我在 angualrjs(登录工厂)中使用的代码:
API 中的 CORS 实现 - 引用目的:
使用方法一:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
EnableCrossSiteRequests(config);
}
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*")
{
SupportsCredentials = true
};
config.EnableCors(cors);
}
}
使用方法二:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
最佳答案
问题源于您的 Angular 代码:
当 withCredentials
设置为 true 时,它会尝试随请求发送凭据或 cookie。因为这意味着另一个来源可能会尝试执行经过身份验证的请求,所以不允许将通配符 (“*”) 作为“Access-Control-Allow-Origin” header 。
您必须明确响应在“Access-Control-Allow-Origin” header 中发出请求的来源,才能使这项工作正常进行。
我会建议将您希望允许发出经过身份验证的请求的来源明确列入白名单,因为简单地使用来自请求的来源进行响应意味着如果用户恰好拥有有效的 session 。
我在 this article 中解释了这些东西我前一段时间写过。
因此,您可以将 withCredentials
设置为 false 或实现来源白名单,并在涉及凭据时使用有效来源响应 CORS 请求
关于javascript - CORS:凭据模式为 'include',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42803394/