春季应用中的CORS政策阻止了来自角度应用的请求

时间:2019-04-04 20:43:17

标签: java angular spring http cross-domain

我试图将请求从角度前端发送到Spring后端公开的REST控制器。 REST控制器具有@CrossOrigin批注。

我正在使用HttpClient从angular应用发送请求。

请求:

  const httpOptions = {
      headers: new HttpHeaders({
        'Authorization': 'Basic ' + basicAuthHeader,
      })
    };
    return this.http.get(this.address + this.addressStorage.loginEndpoint + '/' + playerName, httpOptions);

结果:

Access to XMLHttpRequest at 'xxx' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Postman发送的相同请求给出正确的答复。

我的假设:

我已经使用chrome开发工具检查了“网络”标签: screen of network tab

是由于发送OPTIONS请求而不是GET请求而导致的问题,并且 CORS只允许使用GET方法吗?

假设我的猜测是正确的,那么是否将该组件添加到Spring Boot应用程序中可以解决我的问题?

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    } 

不幸的是,我目前无法更改后端实现,所以我自己也找不到它。

其他信息:

  registerPlayer(player: PlayerDTO): Observable<Object> {
    const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json'}),
    };
    return this.http.post(this.address + this.addressStorage.createUserEndpoint, player, httpOptions);
  }

此请求发送到同一控制器,但在不同端点上返回正确的响应。

1 个答案:

答案 0 :(得分:1)

我相信您的服务器发送Access-Control-Allow-Credentials意味着您还需要通知服务以'Access-Control-Allow-Credentials': 'true'发送请求

更新

  

凭据请求和通配符   当响应凭证请求时,服务器必须在Access-Control-Allow-Origin标头的值中指定一个来源,而不是指定“ *”通配符。   Preflighted requests