Skip to content

Spring Boot CORS 跨域请求

🏷️ Spring Boot

1. 配置全局的 GlobalCorsConfig

java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        //1.添加 CORS 配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOrigin("*");
        //是否发送 Cookie 信息
        config.setAllowCredentials(true);
        //放行哪些原始域 (请求方式)
        config.addAllowedMethod("*");
        //放行哪些原始域 (头部信息)
        config.addAllowedHeader("*");
        //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
        config.addExposedHeader("Content-Type");
        config.addExposedHeader("X-Requested-With");
        config.addExposedHeader("accept");
        config.addExposedHeader("Origin");
        config.addExposedHeader("Access-Control-Request-Method");
        config.addExposedHeader("Access-Control-Request-Headers");

        //2.添加映射路径
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的 CorsFilter.
        return new CorsFilter(configSource);
    }
}

2. 自定义的 filter 中过滤 OPTIONS 请求

有些浏览器会发送一个 OPTIONS 预检请求到服务器,此时 body 是空的。

可以通过判断请求的 method 是否为 OPTIONS 来判断。示例代码如下:

java
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;

    if (request.getMethod().equalsIgnoreCase("OPTIONS"))
        chain.doFilter(request, response);
        return;
    }
}

参考

  1. SpringBoot 实现前后端分离的跨域访问(CORS)
  2. 38.Spring Boot 与 Vue 跨域的问题