Angular 7 HttpClient post 响应 headers 为空

Angular 7 HttpClient post response headers are empty

我正在尝试使用 Spring 安全后端从 Angular 7 执行登录:

login(username: string, password: string) {

    const formData = new FormData();
    formData.append('username', username);
    formData.append('password', password);

    return this.http.post<UserInfo>(`${API_URL}/login`, formData, {observe: 'response'})
      .pipe(map(response => {

        const jwtToken = response.headers.get(AUTHORIZATION).replace('Bearer', '').trim();
        const userInfo = response.body;

        if (jwtToken && userInfo) {
          const user = new User(username, password, jwtToken, userInfo);
          localStorage.setItem(CURRENT_USER, JSON.stringify(user));
          this.currentUserSubject.next(user);
        }

        return response;
      }));
  }

但是,response.headers 只是空的,不包含任何 header。 Postman 和 Chrome 开发工具显示了许多 header,甚至是我需要的 - 授权。我已经审查了许多 SO 问题和 github 问题,但他们都说同样的话,这对我不起作用 - 简单地列出 CORS Access-Control-Expose-Headers 中的 header,但我已经完成了那并没有改变。这是相关的 Spring 配置:

@Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("http://localhost:4200");
        configuration.addExposedHeader("Authorization");
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

此时我卡住了,不知道如何让 Angular 访问那些 headers:

您需要 authorization header,您可以通过 response.headers.get("Authorization") 获得。尝试:

const jwtToken = response.headers.get("Authorization").replace('Bearer', '').trim();

在服务器端你需要配置"Access-Control-Allow-Headers"。参考这个 post: .

对我来说,这个配置很管用:

@Bean
CorsConfigurationSource corsConfigurationSource() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addExposedHeader(
            "Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, "
                    + "Content-Type, Access-Control-Request-Method, Custom-Filter-Header");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("DELETE");
    source.registerCorsConfiguration("/**", config);
    return source;
}