后端接口服务在跟h5交互的时候POST请求,复杂请求会有一次OPTIONS请求,但是小概率出现只有OPTIONS,然后就没有POST了,OPTIONS是返回正常的状态码,这种问题出现的原因是什么呢?目前貌似只有上传文件接口出现了该问题
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
response.setHeader("Access-Control-Allow-Origin", "*");
// 允许的访问方法
response.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE, PATCH");
// Access-Control-Max-Age 用于 CORS 相关配置的缓存
response.setHeader("Access-Control-Max-Age", "86400");
response.setHeader("Access-Control-Allow-Headers","token,Origin, X-Requested-With, Content-Type, Accept");
if(HttpMethod.OPTIONS.name().equals(request.getMethod().toUpperCase())){
response.setStatus(HttpStatus.SC_NO_CONTENT);
filterChain.doFilter(request,response);
}
boolean check = false;
String token = request.getHeader("token");
if(StringUtils.isNotBlank(token)){
long mobile = redisProxy.getMobileByToken(token);
if(mobile > 0){
// token验证成功
check = true;
request.setAttribute(Constant.REQUEST_UM5, Md5Util.getMd5(mobile));
}
}
if(check){
filterChain.doFilter(request,response);
}else {
//验证不通过 返回需要登录的状态码
ResponseView responseView = new ResponseView(ResultType.NEED_LOGIN);
String resultStr = JSON.toJSONString(responseView);
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(resultStr);
writer.flush();
} catch (IOException e) {
log.error("filter error:{}",e);
}finally {
if(writer != null ){
writer.close();
}
}
}
}