jq ajax自定义请求头
$.ajax({
type: "POST",
headers: {
Accept: "application/json; charset=utf-8",
Token: "xxx" //这个是自定义的请求头
},
url: "XXX",
contentType: "application/json",
data: JSON.stringify(str),//将变量str转为json数据,可忽略
dataType: 'json',
success: function(result) {
if(result.code == 200) {//200:请求成功
consile.log("ok");
}
}
});
下面是过滤器的一个设置
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Token");
//自定义跨域请求浏览器会先发送一个OPTIONS请求,服务器要对其作出相应,浏览器才会正常发出请求
if (req.getMethod().equals("OPTIONS")) {
//设置响应状态码
res.setStatus(200);
return;
}
}
到这里完成了配置
实例
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");//是否允许发送Cookie
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
//对客户端自定义请求头的应答
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Token");
/**
* 针对自定义header问题
* 客户端错误:Request header field Token is not allowed by Access-Control-Allow-Headers in preflight response.
* 原因:包含自定义header字段的跨域请求,浏览器会先向服务器发送OPTIONS请求,探测该服务器是否允许自定义的跨域字段。
* 如果允许,则继续实际的POST/GET正常请求,否则,返回标题所示错误。
*/
if (req.getMethod().equals("OPTIONS")) {
//设值响应状态码
res.setStatus(200);
return;
}
chain.doFilter(request, response);
}
相关推荐
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo