springboot 后台允许接受浏览器跨域请求

1.自定义拦截器:

public class CorsInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String origin = httpServletRequest.getHeader("Origin");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin,Content-Type,Accept,token,X-Requested-With");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

        return true;
    }
}

2.在启动类中调用

@Configuration
@EnableAutoConfiguration
@ComponentScan
@MapperScan(value = "com.zijibeyond.mapper")

public class Example extends WebMvcConfigurationSupport {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CorsInterceptor()).addPathPatterns("/**");
    }
}

 

你可能感兴趣的:(springboot 后台允许接受浏览器跨域请求)