跨域请求时的JAVA设置

response 对象设置返回响应头 header

设置项有下面这几项

response.setHeader("Access-Control-Allow-Origin", originHeader);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "content-type");
response.setHeader("Access-Control-Allow-Credentials", "true");

普通的跨域请求,如 GET, POST

response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods", "*");

POST 请求的时候,会先发送 OPTIONS 请求, 设置预请求缓存1个小时,1个小时内不再发送OPTIONS请求

response.setHeader("Access-Control-Max-Age", "3600");

特殊的请求头,需要明确写上,后台才能接收到, 如 content-type

response.setHeader("Access-Control-Allow-Headers", "content-type");

跨域请求时带cookie, 需要设置接收 cookie 的设置 Credentials,并且明确写明接收的 IP地址

response.setHeader("Access-Control-Allow-Origin","http:yourip");
response.setHeader("Access-Control-Allow-Credentials", "true");

需要设置多个IP,参考 获取session

前端需要取某些header,必须后端提供Access-Control-Expose-Headers,前端才能拿到。

response.setHeader("Access-Control-Expose-Headers", "need-header-name")

以上的设置都是在java代码上做的,还可以在 Nginx 上进行配置

SpringBoot 配置

Controller层代码: @CrossOrigin

@RequestMapping("/demo")
@RestController
@CrossOrigin("https://blog.csdn.net") // 只有这个指定域名可以访问该类下所有接口
public class CorsTestController {
  @GetMapping("/sayHello")
  public String sayHello() {
    return "hello world !";
  }
}

CORS全局配置

新建跨域配置类:CorsConfig.java

@Configuration
public class CorsConfig implements WebMvcConfigurer {
 @Bean
  public WebMvcConfigurer corsConfigurer(){
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/*"). allowedOrigins("https://www.dustyblog.cn").  //允许跨域的域名,可以用表示允许任何域名使用
        allowedMethods(""). //允许任何方法(post、get等) allowedHeaders(""). //允许任何请求头
        allowCredentials(true). //带上cookie信息
        exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
      }
    };
  }
}

拦截器实现

通过实现Fiter接口在请求中添加一些Header来解决跨域的问题

@Component
public class CorsFilter implements Filter {
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse res = (HttpServletResponse) response;
    res.addHeader("Access-Control-Allow-Credentials", "true");
    res.addHeader("Access-Control-Allow-Origin", "*");
    res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
    if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
        response.getWriter().println("ok");
        return;
    }
    chain.doFilter(request, response);
}
  @Override
    public void destroy() {
  }
  @Override
    public void init(FilterConfig filterConfig) throws ServletException {
  }
}

参考:

https://blog.csdn.net/weixin_42036952/article/details/88564647