1,服务器端要支持跨域
response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
2.服务器端要支持接收cookie
response.setHeader("Access-Control-Allow-Credentials", "true");
3,前端发送ajax时声明传递cookie
var testCrossDomain=function () {
var options = {
url: "http://ccc.ddd.com/convention2/test/324/json",
type: "get",
xhrFields: {
withCredentials: true
},
crossDomain: true,
dataType: 'json',
success: function (json2) {
console.log(json2)
},
error: function (er) {
console.log(er)
}
};
$.ajax(options);
}
注意:
1,跨域传递cookie时,
"Access-Control-Allow-Origin"
不能指定*,也不能指定多个域名,否则浏览器报错:
问题:
Failed to load http://stub.yhskyc.com/stub/api/appList.json?_mock=false&_stamp=1538383965103: The value of the 'Access-Control-Allow-Credentials' header in the response is 'false' which must be 'true' when the request's credentials mode is 'include'. Origin 'http://xxx.com' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
原因:
前端 ajax 请求时设置 withCredentials 值为'include',但是后台服务器端没有设置'Access-Control-Allow-Credentials',或这是'Access-Control-Allow-Credentials' 值为false
解决方法:
后端增加全局filter:/src/main/java/com/common/web/filter/SimpleCORSFilter.java
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
if (request.getServletPath().endsWith("/cors/update/json")) {
chain.doFilter(req, res);
return;
}
//优先级 request > header
String allOrigin = ObjectUtils.firstNonNull(request.getParameter("allowOrigin"), request.getHeader("Origin"), this.allowOriginDto.getAccessControlAllowOrigin());
System.out.println(message);
response.setHeader("Access-Control-Allow-Origin", allOrigin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
String allCookie = request.getParameter("allowCookie");
if ("true".equalsIgnoreCase(allCookie)) {//允许客户端带cookie
response.setHeader(Const.HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
} else {
response.setHeader(Const.HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS, String.valueOf(this.allowOriginDto.getAccessControlAllowCredentials()));
}
chain.doFilter(req, res);
}
注意:
1,后端设置 Access-Control-Allow-Origin时,必须包含协议
正确:Access-Control-Allow-Origin=http://www.aaa.com
错误:Access-Control-Allow-Origin=www.aaa.com
2,设置 Access-Control-Allow-Credentials 为true
参考:https://github.com/liuyu520/common_ssh