Spring BOOT Cors过滤器选项错误“对预检请求的响应未通过访问控制检查”

时间:2019-09-23 11:55:14

标签: reactjs spring-boot

我一直在尝试解决该cors错误达数小时之久,并且尝试了所有可能的解决方案,除了一个(它为每个资源/请求添加了options方法)。

Cors配置类

@Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
    return new WebMvcConfigurer()  {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedHeaders("*")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                    .allowCredentials(true)
                    .allowedOrigins("*")
                    .exposedHeaders(AuthorizationController.AUTHENTICATION_KEY_NAME + "," +
                                    HandlerHelper.REASON_KEYNAME)
                    .maxAge(3600);
        }
     };
    }


}

预处理

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Origin","*");
    response.setHeader("Access-Control-Allow-Methods" ,"GET, POST, PUT, DELETE, OPTIONS");
    response.setHeader("Access-Control-Allow-Headers",AuthorizationController.AUTHENTICATION_KEY_NAME +","+ REASON_KEYNAME);
    response.setHeader("Access-Control-Max-Age","3600"); }

application.properties

spring.mvc.dispatch-options-request=true

将注释添加到类,并将OPTIONS方法添加到每个资源的任何请求

 @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/**", method = RequestMethod.OPTIONS)
        public ResponseEntity handle() {
            return new ResponseEntity(HttpStatus.OK);
        }

我如何在Spring Boot中允许“ not simple cors request”?还是这个react问题?我的前端开发人员无法从axios发送请求。

1 个答案:

答案 0 :(得分:0)

在下面添加代码可解决此问题。

@EnableWebSecurity
public static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // ...
        http.cors().and().csrf().disable();
    }
}