如何解决Angular 9-打字稿-headers.set-不添加标题
我尝试使用有角的注入器添加不记名令牌
尽管代码已执行,但未添加标头
有很多不同的代码,我尝试了其中的一些,它们都导致相同的问题
没有发送承载与请求
在下图中,我在 clone / headers.set 处停了下来,但是即使经过这一步,标题映射仍然为空
@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()方法原型,您获得了一个对象属性来设置标头(名为setHeaders)
setHeaders?: {
[name: string]: string | string[];
};
您应该执行以下操作
request = request.clone(
{
setHeaders: {
Authorization: `Bearer ${authentication.token}`
}
}
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。