[英]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 只是空的並且不包含任何標題。 Postman 和 Chrome 開發工具顯示了許多標題,甚至是我需要的標題 - 授權。 我已經審查了許多 SO 問題和 github 問題,但它們都說同樣的話,這對我不起作用 - 簡單地在 CORS Access-Control-Expose-Headers 中列出標題,但我已經這樣做了並且沒有任何改變。 這是一個相關的 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 訪問這些標頭:
您需要authorization header
,您可以通過response.headers.get("Authorization")
。 嘗試:
const jwtToken = response.headers.get("Authorization").replace('Bearer', '').trim();
在服務器端,您需要配置“Access-Control-Allow-Headers”。 請參閱這篇文章: Angular 6 Get response headers with httpclient issue 。
對我來說,這個配置成功了:
@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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.