Vue 项目中遇到的跨域问题
把 withCredentials: true 改成 withCredentials: false,如果你没加上面那段代码当然也不会报这个错。虽然是解决方法很简单,但经此发现许多知识没掌握不得不梳理下。
HTTP 请求方式有许多种,有些请求会触发 CORS 预检请求。“需预检的请求”会使用 OPTIONS 方法发起一个预检请求到服务器,以获知服务器是否允许该实际请求。
对于跨域请求浏览器一般不会发送身份凭证信息。如果要发送凭证信息,需要设置 XMLHttpRequest 的 withCredentials 属性为 true:withCredentials: true。此时要求服务器的响应信息中携带 Access-Control-Allow-Credentials: true,否则响应内容将不会返回。
对于携带身份凭证的请求,服务器不得设置 Access-Control-Allow-Origin 的值为“*”。因为请求头携带了 Cookie 信息。要将 Access-Control-Allow-Origin 的值设置为<origin>域名。
另外,响应头中也携带了 Set-Cookie 字段,尝试对 Cookie 进行修改。如果操作失败,将会抛出异常。
跨域请求想要带上 cookies 必须在请求头里面加上:crossDomain: true,
xhrFields: {
withCredentials: true
╮(╯▽╰)╭ 又变成文章开头的问题了,解决办法:
后台代码:
Access-Control-Allow-Origin: <origin>域名
Access-Control-Allow-Credentials: true
前端代码:
crossDomain: true,
xhrFields: {
withCredentials: true
跟之前一样就行了。
WEPAPI 后端
1,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);
}
}
2, public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}