原文:https://www.jb51.net/article/137278.htm前端
问题描述
前端 vue 框架,跨域问题后台加这段代码 header("Access-Control-Allow-Origin: *"); 加了以后报这个错:vue
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'. 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'.
解决办法
文章连接:CORS: credentials mode is ‘include'json
xhrFields: { withCredentials: false },
把 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 的值设置为 http://www.zrt.local:8080。
另外,响应头中也携带了 Set-Cookie 字段,尝试对 Cookie 进行修改。若是操做失败,将会抛出异常。
跨域请求想要带上 cookies 必须在请求头里面加上:浏览器
crossDomain: true, xhrFields: { withCredentials: true }
又变成文章开头的问题了,解决办法:服务器
后台代码:cookie
Access-Control-Allow-Origin: 'http://www.zrt.local:8080' Access-Control-Allow-Credentials: true
前端代码:app
crossDomain: true, xhrFields: { withCredentials: true }
跟以前同样就好了。框架
总结
1.不限定跨域地址,不携带身份凭证
.NET COREui
services.AddCors( options => options.AddPolicy( _defaultCorsPolicyName, builder => builder .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() ) );
PHP后台代码:
header("Access-Control-Allow-Origin: *");
前端代码:
xhrFields: { withCredentials: false },
2.指定受权访问地址,携带身份凭证(带cookies)
.NET CORE
services.AddCors( options => options.AddPolicy( _defaultCorsPolicyName, builder => builder .WithOrigins( // App:CorsOrigins 在 appsettings.json 中,可配多个地址 _appConfiguration["App:CorsOrigins"] .Split(",", StringSplitOptions.RemoveEmptyEntries) .Select(o => o.RemovePostFix("/")) .ToArray() ) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() ) );
PHP后台代码:
Access-Control-Allow-Origin: 'http://www.zrt.local:8080' Access-Control-Allow-Credentials: true
前端代码:
crossDomain: true, xhrFields: { withCredentials: true }