String origin = reqs.getHeader("origin");// 获取源站
String requestHeaders = reqs.getHeader("Access-Control-Request-Headers");
if (StringUtils.isEmpty(requestHeaders)) {
requestHeaders = "";
}
httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "HEAD,PUT,DELETE,POST,GET");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Accept, Origin, XRequestedWith, Content-Type, LastModified," + requestHeaders);
Access to XMLHttpRequest at 'http://10.10.1.49:9000/liinji_mobile_web/SelfInspection/getSelfInspection' from
origin 'http://localhost:63342' has been blocked by CORS policy: Response to preflight request doesn't pass access control check:
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 credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.
当请求的凭据模式为include时,相应中的Access-Control-Allow-Origin标头的值不能是通配符 “*”
如在请求定义中设置withCredentials标志,则会在请求中传递cookie等。
如果服务器返回任何set-cookie响应头, 那么必须返回Access-Control-Allow-Credentials: true, 否则将不会在客户端上创建 cookie
如果你这样设置,你需要同时指定了确切的Access-Control-Allow-Origin响应头,因为Access-Control-Allow-Origin: 不具有凭证兼容
所以当请求中携带cookie时, Access-Control-Allow-Origin必须要有确切的指定, 不能是通配符(*), 而withCredentials是跨域安全策略的一个东西
鉴于网上大部分(如下)
// 普遍通配符*
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");
所以个人感觉如果有需求的话建议使用
String origin = request.getHeader("origin");// 获取源站
httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
Access to XMLHttpRequest at 'http://10.10.1.49:9000/liinji_mobile_web/SelfInspection/getSelfInspection' from
origin 'http://localhost:63342' has been blocked by CORS policy: Request header field Token is not allowed by
Access-Control-Allow-Headers in preflight response.
大概意思是Request Headers中的Access-Control-Request-Headers与Response Headers中的Access-Control-Allow-Headers不一致导致的,如图
由于Request Headers中的Access-Control-Request-Headers各种各样的都有,所以个人建议如下
// 获取request中的Access-Control-Request-Headers参数
String requestHeaders = request.getHeader("Access-Control-Request-Headers");
if (StringUtils.isEmpty(requestHeaders)) {
requestHeaders = "";
}
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Accept, Origin, XRequestedWith, Content-Type, LastModified," + requestHeaders);