原本服务端注册了这样一个过滤器支持跨域
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 服务端允许跨域
*/
public class CrosFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
//允许所有域对本域的跨域请求
res.addHeader("Access-Control-Allow-Origin", "*");
//不论是get post 所有方法都允许跨域
res.addHeader("Access-Control-Allow-Methods", "*");
String headers = req.getHeader("Access-Control-Request-Headers");
// 支持所有自定义头
if (!org.springframework.util.StringUtils.isEmpty(headers)) {
res.addHeader("Access-Control-Allow-Headers", headers);
}
res.addHeader("Access-Control-Max-Age", "3600");//options预检命令缓存一小时
chain.doFilter(request, response);
}
@Override
public void destroy() {}
}
前端请求
$.ajax({
type : "get",
url: "http://localhost:8080/test/getCookie",
success: function(json){
result = json;
}
});
后端对应这个方法↓
@GetMapping("/getCookie")
public ResultBean getCookie(@CookieValue(value = "cookie1") String cookie1) {
System.out.println("TestController.getCookie()");
return new ResultBean("getCookie " + cookie1);
}
这样浏览器会报错 400错误 -请求无效
因为请求没有带cookie , 就没有映射到这个contoller方法
前端加一个
xhrFields:{withCredentials:true},//带上cookie去请求
$.ajax({
type : "get",
url: "http://localhost:8080/test/getCookie",
xhrFields:{
//带上cookie
withCredentials:true
},
success: function(json){
result = json;
}
});
服务端也相应的 在过滤器里面加个头
// enable cookie
res.addHeader("Access-Control-Allow-Credentials", "true");
这样仍然不行
浏览器报错
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'.
就是说 这样加头 用通配符 在带cookie的时候不行
//允许所有域对本域的跨域请求
res.addHeader("Access-Control-Allow-Origin", "*");
那就改成
HttpServletResponse res = (HttpServletResponse) response;
String origin = req.getHeader("Origin");
if (!org.springframework.util.StringUtils.isEmpty(origin)) {
res.addHeader("Access-Control-Allow-Origin", origin);//加这个头表示:允许这个域 跨域访问
}
注意
服务端 就是http://localhost:8080 这里必须真的有cookie 叫cookie1
document.cookie="cookie1=xiaofengqing"