带Cookie的跨域Ajax请求
客户端
$.ajax({
url : 'http://www.xxx.com/corsrequest',
data : data,
dataType: 'json',
type : 'POST',
//允许携带证书
xhrFields: {
withCredentials: true
},
//允许跨域
crossDomain: true,
contentType: "application/json",
...
通过设置 withCredentials: true ,发送Ajax时,Request header中便会带上 Cookie 信息。
服务器端
相应的,对于客户端的参数,服务器端也需要进行设置:
/**
* Spring Controller中的方法:
*/
@ResponseBody
public Map<String, Object> getUserBaseInfo(HttpServletResponse response) {
if(request.getHeader("Origin").contains("woego.cn")) {
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
}
response.setHeader("Access-Control-Allow-Credentials", "true");
...
}
在使用Ajax跨域请求时,如果设置Header的ContentType为application/json,会分两次发送请求。第
一次先发送Method为OPTIONS的请求到服务器,这个请求会询问服务器支持哪些请求方法(GET,POST等),
支持哪些请求头等等服务器的支持情况。等到这个请求返回后,如果原来我们准备发送的请求符合服务器的规
则,那么才会继续发送第二个请求,否则会在Console中报错。 https://www.jianshu.com/p/fddd19669ab3
浙公网安备 33010602011771号