Ajax跨域Options请求携带自定义header后台接收不到
背景
因为需要跨项目调用,为了简便起见,没有使用Fegin来调用,如果使用Feign还需要再重新实现一套逻辑,所有就直接从A项目使用Ajax调用B项目中已实现的接口。
项目A中使用了单点登录,所有请求都会做一次拦截,所以在B中调用的时候加入了一个自定义的header,以此来校验是来自于B项目中的调用请求;
A项目中的前端调用:
$.ajax({
url: 'http://ip:port/a/b', //请求地址
type: "POST",
// contentType: 'application/json',
contentType: 'application/x-www-form-urlencoded',
data:data,//data为json字符串
headers: {
"testheader": "test",
},
dataType: "json",
success: function (json) {
console.log(json)
}
})
B项目中需要加入拦截器:
public class HeadersCorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
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", "Origin, X-Requested-With, Content-Type, Accept, " +
"WG-App-Version, WG-Device-Id, WG-Network-Type, WG-Vendor, WG-OS-Type, WG-OS-Version, WG-Device-Model, WG-CPU, WG-Sid, WG-App-Id, WG-Token,testheader");
response.setHeader("Access-Control-Allow-Credentials","true");
//对于OPTIONS的请求放行
if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
注意:
1、在服务端处理过程时,在响应头中增加以下几部分的内容即可:
Access-Control-Allow-Origin服务器能接受的跨域请求来源,配置主机地址(http://www.xxx.com,如有端口也要加上), * 表示任意地址都行
Access-Control-Allow-Headers 表示能接受的http头部,此处要加入你自己构建的头部字段,如上面的testheader
Access-Control-Allow-Methods 表示能接受的http mothed ,看使用情况加上,如GET、POST、OPTIONS等
2、对于非简单的请求,会进行两次请求,第一次是发送options
,确认成功了再发送请求,第一次请求是不携带数据的,包括header的数据;
对于简单请求和复杂请求可以参考:https://www.jianshu.com/p/b0aeeb712c62
3、一定记得加入这段代码
if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(request, response);
}