springboot自定义过滤器Filter进行JWT登陆令牌验证并设置响应头实现跨域失效是因为服务端未处理浏览器发送的预检请求。
cors有两类请求:1 简单请求 2 非简单请求
只要同时满足以下两大条件,就属于简单请求。
- 请求方法是以下三种方法之一:
HEAD
GET
POST - HTTP的头信息不超出以下几种字段:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain
凡是不同时满足上面两个条件,就属于非简单请求。
解决方案:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws JsonProcessingException, IOException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with");
httpResponse.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST,DELETE,PUT");
chain.doFilter(request, response);
}
网友评论