Angular 5 + HttpClient不会在GET上发送Headers

时间:2018-04-29 19:06:44

标签: angular angular5

我正在使用Angular 5 https://angular.io/api/common/http/HttpClient#get[1]来执行HTTP GET请求,该请求需要授权标头。

有人可以在此代码中指出问题吗?感谢。

this.http.get<Company[]>('http://localhost:8080/api/company/list',
      {
        headers:
          {'Authorization': 'Bearer 56155553-87f8-47f3-be87-8a4acf4ccacf'}
      })
      .subscribe(companies => {
        this.companies = companies;
        // Calling the DT trigger to manually render the table
        this.dtTrigger.next();
      });

我收到以下错误,我怀疑标题未正确传递。

XMLHttpRequest cannot load http://localhost:8080/api/company/list. Response for preflight has invalid HTTP status code 401

仅供参考:Bearer令牌和CORS配置没有问题。

在服务器端,我使用过Spring Boot。以下是我添加的CORS配置。

@Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, Authorization, X-Custom-Header");

        chain.doFilter(req, res);
    } 

1 个答案:

答案 0 :(得分:2)

浏览器正在发出OPTIONS请求以请求使用自定义HTTP标头(即授权标头)发出请求的权限。

服务器正在响应401(未授权)错误。

您需要从要求授权的要求中排除OPTIONS请求。