Spring MVC CORS不适用于错误控制器

Spring MVC CORS不适用于错误控制器,spring,spring-mvc,Spring,Spring Mvc,我将Spring MVC应用程序配置为使用CORS,如下所示: @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**"); } 这对于成功的请求很好,但是当抛出异常并由我的错误处理程序拾取时,不会添加CORS头 @ControllerAdvice public class ApiErrorHandler { @ExceptionHandler(value =

我将Spring MVC应用程序配置为使用CORS,如下所示:

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**");
}
这对于成功的请求很好,但是当抛出异常并由我的错误处理程序拾取时,不会添加CORS头

@ControllerAdvice
public class ApiErrorHandler {

   @ExceptionHandler(value = HttpClientErrorException.class)
   public ResponseEntity badRequest(Exception ex) 
   {
       return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ErrorBodyWrapper.wrapErrorInJson(ex.getMessage()));
   }
}
CORS不适用于错误处理程序有什么原因吗


谢谢

我认为默认情况下,添加到映射的唯一方法是GET, 在“addCorsMappings”中,尝试指定要将标题添加到的方法

       registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
你也一样

@Configuration
public class ManagerWarInit extends WebMvcConfigurerAdapter {

    ... 

    private static final String[] SUPPORT_METHODS = new String[] {
            HttpMethod.HEAD.name(),
            HttpMethod.OPTIONS.name(),

            HttpMethod.GET.name(),
            HttpMethod.POST.name(),

            HttpMethod.PUT.name(),
            HttpMethod.DELETE.name()
    };
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods(SUPPORT_METHODS)
                .exposedHeaders("Set-Cookie");
    }
}
和全球感受

@ControllerAdvice
public class ManagerGlobalException {

    // @CrossOrigin(...)
    @ExceptionHandler(NotLoginException.class)
    public void noLogin(NotLoginException e, HttpServletResponse response)
                       throws IOException {
        if (LOG.isDebugEnabled())
            LOG.debug(e.getMessage());

        if (RequestUtils.isAjaxRequest()) {
            RequestUtils.toJson(notLogin(), response);
        } else {
            response.sendRedirect("hxxp://www.xxx.com");
        }
    }
}
但浏览器(Chrome等)的跨域调用错误

XMLHttpRequest无法加载hxxp://127.0.0.1:8080/url... 请求的资源上不存在“Access Control Allow Origin”标头。起源'hxxp://127.0.0.1:3000因此,不允许访问。

尝试在ExceptionHandler上添加
@CrossOrigin
批注时仍存在此错误

我现在正在处理这个问题

@ControllerAdvice
public class ManagerGlobalException {

    @ExceptionHandler(NotLoginException.class)
    public String notLogin(NotLoginException e) throws IOException {
        if (LOG.isDebugEnabled())
            LOG.debug(e.getMessage());

        if (RequestUtils.isAjaxRequest()) {
            return "forward:/not-login";
        } else {
            return "redirect:hxxp://www.xxx.com";
        }
    }
}
添加映射

@RestController
public class IndexController {

    @RequestMapping(value = "/not-login")
    public JsonResult notLogin() {
        return JsonResult.notLogin();
    }
}

使用Spring
CorsFilter
可以解决此问题

@Bean
公共过滤器注册Bean公司过滤器(){
UrlBasedCorsConfigurationSource=新的UrlBasedCorsConfigurationSource();
CorsConfiguration配置=新的CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin(“*”);
config.addAllowedHeader(“*”);
config.setAllowedMethods(Arrays.asList(“GET”、“POST”、“PUT”、“DELETE”、“OPTIONS”);
source.registerCorsConfiguration(“/**”,config);
FilterRegistrationBean=新的FilterRegistrationBean(新的公司过滤器(源));
设置顺序(0);
返回豆;
}
在mvc中,而不是在springboot中, 一个像垃圾一样的项目,它会杀了我,遇到同样的问题; springmvc.xml来处理CRO,配置如下:

    <mvc:cors>

    <mvc:mapping path="/**"
                 allowed-origins="*"
                 allowed-methods="*"
                 allowed-headers="*"
                 exposed-headers="Access-Control-Allow-Origin,Access-Control-Allow-Credentials"
                 allow-credentials="true"
                 max-age="3600"/>

</mvc:cors>
它起作用了 可能mvcDispatchServlet忘记为异常响应添加cros头, 所以我做了
但是它不够优雅

CORS是一种防止跨域请求的协议,@ControllerAdvice应该从控制器收集异常,这是CORS检查之后的一个步骤,您使用的servlet容器是什么?请求的方法类型是什么?@AmerQarabsa我使用的是嵌入式tomcat。任何方法类型似乎都会失败。。。但我最初使用的是选项。这对于错误响应仍然不起作用。它对于成功的响应非常有效。我在一个拦截器中抛出异常,这会有区别吗?不,不会,实际上错误响应与CORS无关,“返回”重定向:hxxp://www.xxx.com“;”这是与您的服务器不同的域吗?
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
    response.setHeader("Access-Control-Allow-Methods", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.getWriter().write(JSONUtil.toJsonString("xxxxxxx error json result"));