2017-04-09 112 views
0

我有我的Spring MVC应用程序配置为使用CORS这样: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不适用于错误处理程序?

感谢

+0

CORS是跨域请求守卫的协议,您应该@ControllerAdvice收集器例外,它们是CORS检查之后的一个步骤,什么是您正在使用的servlet容器?而这是请求的方法类型? –

+0

@AmerQarabsa我正在使用嵌入式的tomcat。任何方法类型似乎都失败了......但我最初使用OPTIONS。 – FMC

回答

0

我觉得默认的唯一方法添加到映射是GET, 在你的“addCorsMappings”尝试指定要在头部添加到

 registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD"); 
+0

这仍然不适用于错误响应。它适用于成功的回应。我在拦截器中抛出异常,这会有所作为吗? – FMC

+0

不,它实际上错误响应与CORS没有任何关系,“return”redirect:hxxp://www.xxx.com“;”这是与你的服务器不同的域名吗? –

0

相同与方法您。

@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"); 
    } 
} 

和globalException

@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 cannot load hxxp://127.0.0.1:8080/url... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'hxxp://127.0.0.1:3000' is therefore not allowed access.

试图上的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(); 
    } 
}