SpringBoot使用HandlerInterceptor添加跨域信息头

原产地

  1. 有时会添加一个不是映射到请求方法直接返回的拦截器,这个拦截器应该在预验请求拦截器的后边,否则OPTIONS预验请求会被直接返回,带不会跨域信息头
/**
 * 配置拦截器
 *
 * @author yujie
 */
@Configuration
public class SystemWebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new HandlerInterceptor() {
                    final public static String OPTIONS = "OPTIONS";

                    @Override
                    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {
                        response.addHeader("Access-Control-Allow-Origin", "*");
                        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
                        response.addHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
                        response.addHeader("Access-Control-Max-Age", "3600");
                        if (OPTIONS.equals(request.getMethod())) {
                            response.setStatus(HttpServletResponse.SC_OK);
                            return false;
                        }
                        return true;
                    }
                })
                .addPathPatterns("/**");

        // 注意顺序,这个应低于上边的复杂请求严重
        registry.addInterceptor(new HandlerInterceptor() {
                    @Override
                    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
                        // 如果不是映射到方法直接拒绝
                        return handler instanceof HandlerMethod;
                    }
                })
                .addPathPatterns("/**");
    }
}
  1. 也可使用nginx代理同意处理头信息
上一篇:项目细节


下一篇:HandlerInterceptor 自定义拦截器