美文网首页
springboot 处理cors预检请求

springboot 处理cors预检请求

作者: 王剑_a9e1 | 来源:发表于2019-03-11 03:17 被阅读0次

    springboot自定义过滤器Filter进行JWT登陆令牌验证并设置响应头实现跨域失效是因为服务端未处理浏览器发送的预检请求。

    cors有两类请求:1 简单请求 2 非简单请求
    只要同时满足以下两大条件,就属于简单请求。

    1. 请求方法是以下三种方法之一:
      HEAD
      GET
      POST
    2. 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);
    }
    

    相关文章

      网友评论

          本文标题:springboot 处理cors预检请求

          本文链接:https://www.haomeiwen.com/subject/nximpqtx.html