Angular 9 - 打字稿 - headers.set - 不添加 header
Angular 9 - typescript - headers.set - not adding header
我尝试使用 angular 注入器来添加不记名令牌
虽然代码执行了,但是header没有添加
那里有很多不同的代码,我尝试了其中一些,它们都导致了同样的问题
请求
没有发送者
在下图中,我在 clone/headers.set 处停了下来,但是 即使在那一步之后,headers 地图是还是空的
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(
private appService: AppService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if user is logged in and request is to the api url
let authentication: Authentication = this.appService.getUserSession();
const isLoggedIn = authentication && authentication.token;
const isApiUrl = request.url.startsWith(environment.apiUrl);
//------------------------------------- add id's
let body = request.body;
if(!body)
{
body={};
}
body['clientId'] = environment.clientId;
body['clientSecret'] = environment.clientSecret;
request = request.clone({
body: body
});
//--------------------------------------- add jwt
if(authentication)
{
request = request.clone(
{
headers: request.headers.set('Bearer', authentication.token)
}
);
}
return next.handle(request);
}
}
感谢你在这方面帮助我
根据 clone() 方法原型,你得到了一个 object 属性 来设置 headers (名为 setHeaders)
setHeaders?: {
[name: string]: string | string[];
};
您应该按照以下步骤进行
request = request.clone(
{
setHeaders: {
Authorization: `Bearer ${authentication.token}`
}
}
);
我尝试使用 angular 注入器来添加不记名令牌
虽然代码执行了,但是header没有添加
那里有很多不同的代码,我尝试了其中一些,它们都导致了同样的问题
请求
没有发送者在下图中,我在 clone/headers.set 处停了下来,但是 即使在那一步之后,headers 地图是还是空的
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(
private appService: AppService
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if user is logged in and request is to the api url
let authentication: Authentication = this.appService.getUserSession();
const isLoggedIn = authentication && authentication.token;
const isApiUrl = request.url.startsWith(environment.apiUrl);
//------------------------------------- add id's
let body = request.body;
if(!body)
{
body={};
}
body['clientId'] = environment.clientId;
body['clientSecret'] = environment.clientSecret;
request = request.clone({
body: body
});
//--------------------------------------- add jwt
if(authentication)
{
request = request.clone(
{
headers: request.headers.set('Bearer', authentication.token)
}
);
}
return next.handle(request);
}
}
感谢你在这方面帮助我
根据 clone() 方法原型,你得到了一个 object 属性 来设置 headers (名为 setHeaders)
setHeaders?: {
[name: string]: string | string[];
};
您应该按照以下步骤进行
request = request.clone(
{
setHeaders: {
Authorization: `Bearer ${authentication.token}`
}
}
);