【发布时间】:2018-04-19 17:45:21
【问题描述】:
在服务器自动更新令牌的上下文中,我正在努力解决基础问题:从响应中获取标头数据。
这似乎与 CORS 无关,因为我的 Node/express allwos Authorization/x-access-token 并相应地响应(请参阅下面的网络选项卡屏幕截图)。
我希望看到的第一步是从响应中读取标题。请参阅我的代码,它是文档中的样板文件。获取“Content-Length”的事件返回 null。
auth-service.ts
login(username:string, password:string):Observable<boolean>{
this.loggedIn = false;
return new Observable( (observer:Observer<boolean>) => {
const body = {user: username, pwd: password};
const url = this.config.API_ENDPOINT_PUBLIC_AUTH;
this.httpClient.post(url, body, {
responseType: 'text',
observe: "response"
}).first().subscribe(
(response:HttpResponse<string>) => {
// DEBUG
console.log(response.headers.get('Authorization'));
console.log(response.headers.get('X-Test-Header'));
console.log(response.headers.get('Content-length'));
this.token = response.headers.get('Authorization');
this.storeToken(this.token);
this.currentUser = username;
this.loggedIn = true;
this.authChanged$.next('auth');
observer.next(true);
},
(err) => observer.next(false),
() => {},
);
});
}
控制台输出:
空
空
空
将此请求与我的网络选项卡的内容进行比较:
不用说我的 HttpInterceptor 也不起作用 - 在响应中提供“授权”标头后,它使用该值作为新令牌。这是为了实现令牌的自动更新:
token.interceptor.ts
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authService = this.injector.get(AuthService);
const token = authService.getToken();
if(token){
request = request.clone({
setHeaders: { 'x-access-token' : token }
});
}
return next.handle(request).do(
(event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
const response:HttpResponse<any> = (<HttpResponse<any>> event);
const authorizationHeader = response.headers.get('Authorization');
console.log('Authorization header value: ' + authorizationHeader);
if(authorizationHeader){
authService.setToken(authorizationHeader);
}
}
},
(err: any) => {
if (err instanceof HttpErrorResponse){
if (err.status === 401) {
this.router.navigate(['/']);
}
}
});
}
【问题讨论】:
-
会不会和内容类型有关?我看到您在 TS 代码中将响应类型设置为“文本”,但是响应本身是“应用程序/json”。如果我错了,请告诉我!
-
确实很有趣,我没有注意到...我必须将预期类型设置为“字符串”,因为 API 返回一个空正文,只有一个状态 200 和一个包含令牌的标头。如果效果更好,让我尝试 rreturn 一个空的 json。
-
不,没有帮助。无法从响应中读取除“Content-Type”以外的任何标头。
-
我明白了……我再看看
-
好的,刚刚找到原因了。使用答案从格式化功能中受益。感谢您的时间@avilac!
标签: angular angular-http-interceptors angular-httpclient