前后端分离中浏览器请求跨域的headers取不到值的问题



       最近做了个token认证,是前后端分离,大致思路就是用户登陆,成功之后返回token,放在本地sessionstorage中,之后,前端做强求拦截,对于之后的请求,将token信息附加到请求头中。


       为了使请求头中Authorization可以被后端获取到,跨域时候做了如下设置:


@Component
@Order(1)
public class AllowOriginFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request=(HttpServletRequest)req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization,token");
        //response.setHeader("Access-Control-Allow-Headers", "*");
        //response.setHeader("Access-Control-Allow-Credentials", "true");
        String Authorization=request.getHeader("Authorization");
        chain.doFilter(req,res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}


}

   但是对于【复杂的】跨域ajax请求,请求方思路是这样的:先发送一个OPTIONS请求,确认是可以请求的,之后才发送我们真正的get或者post等我们在ajax中定义的请求;第一次OPTIONS请求,headers是不会带过来的,所有,要在过滤器中单独处理这种:


if (httpRequest.getMethod().equals("OPTIONS")) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
        }


   还有一些问题,明天再test。---2017年11月23日00:34:40






你可能感兴趣的:(微服务+容器)