angular - Angular 7 HttpClient 发布响应标头为空
问题描述
我正在尝试使用 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();
推荐阅读
- google-app-engine - Google App Engine 不适用于 GoDaddy 注册的自定义域
- java - Int 值的用户输入的冒泡排序数组
- python - 使用python构建拓扑时映射错误
- python - 需要重复Flask表单,一个表单类的多个实例
- jquery - 如何隐藏和预设标签jquery css
- unix - 将大文件拆分为具有一定数量记录的较小文件(awk,unix)
- php - php从嵌套的多维数组中删除重复项
- ios - [React Native][IOS] 应用被通知打开时如何捕捉事件
- python - Python unittest AssertionError
> != - php - 更新 PHP7 后的 Opcache 不显示在 phpinfo 中