トークンを自動的に更新するサーバーのコンテキストでは、基本から悩んでいます。角4:応答からヘッダーを読み取ることができません - CORSの問題ではありません
私のNode/expressが承認/ xアクセストークンとそれに応じた応答をすべて受けているため、CORSに関連していないようです(下記のネットワークタブのscreeencapを参照してください)。
作業を確認したい最初のステップは、応答からヘッダーを読み取るだけです。私のコードを参照してください、それはドキュメントにある定型句です。イベント "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(['/']);
}
}
});
}
は、それがコンテンツタイプに関連付けることでした:
あなたのノード/ Expressのアプリ(コメント "HERE SOLUTION" を探してください)を設定しますか?私はTSコードで応答タイプを "テキスト"として設定していますが、応答自体は "application/json"となります。私は間違っている場合私に教えて! – avilac
確かにinterresting、私は気づきませんでした... APIがヌルボディ、ステータス200とトークンを含むヘッダーを返すので、予想される型を "文字列"に設定する必要がありました。それがうまくいくなら、空のjsonをrreturnで試してみましょう。 – Jem
いいえ、役に立たない。レスポンスから 'Content-Type'以外のヘッダーを読み取ることはできません。 – Jem