gpt4 book ai didi

Angular HttpInterceptor 不更改 header

转载 作者:太空狗 更新时间:2023-10-29 17:58:55 29 4
gpt4 key购买 nike

我编写了一个 Angular (4.3.6) HttpInterceptor 来添加一些 header 字段,但如果我在调试器中检查它们,则 header 不会更新。有什么想法吗?

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {


intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

console.log('AuthInterceptor at work');

const contentTypeReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
});

const token = localStorage.getItem('token');
if (token) {
const authReq = contentTypeReq.clone({
headers: req.headers.set('Authorization', 'Bearer ' + token)
});
return next.handle(authReq);
}

// Pass on the cloned request instead of the original request.
return next.handle(contentTypeReq);
}
}

最佳答案

他们很懒惰。例如keys method看起来像:

keys(): string[] {
this.init(); <== initialize

return Array.from(this.normalizedNames.values());
}

如果你想检查它们,只需调用:

req.headers.keys()

如果你想检查值,你可以使用 getgetAll 方法:

req.headers.getAll('Content-Type')

或者您可以从控制台调用init 方法,然后您将能够在headers Map 中看到标题

enter image description here

而且当angular adds headers to request它使用 forEach也调用 init 方法的方法。

关于Angular HttpInterceptor 不更改 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46418746/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com