angular - 拦截器不添加标头来获取请求
问题描述
我做了这个拦截器:
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
export class AddHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header
if (req.url.includes('GetFriend')){
req = req.clone({
setHeaders: {
'Content-Type' : 'application/json; charset=utf-8',
'Accept' : 'application/json',
'Authorization': `Bearer ${sessionStorage.getItem("token")}`
}
});
return next.handle(req);
}
return next.handle(req);
}
}
该提供商:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AddHeaderInterceptor, multi: true },
],
这就是获取请求,需要标头:
this.http.get('http://localhost:52575/api/account/GetFriends').subscribe((res: FriendsList)=>{
this.friends = res;
});
我查看了 Fiddler,我向服务器发送了哪些包,没有关于添加的标头的任何信息,服务器向我发送此错误“HTTP/1.1 401 Unauthorized”:
解决方案
推荐阅读
- c - 有没有更简单的方法将以下数据输入到结构中?
- python - angular.js 网站上的 Selenium click() 方法
- ios - 在绘制之前根据 UITableViewHeight 设置 UITableViewCell 高度
- java - 通过 JSch 建立 2 个网关的 SSH 隧道
- python - 有人可以帮助找出我的hackerrank频率查询代码中的问题吗?
- audio - 使用 cue 拆分 flac 文件:shnsplit failed
- wordpress - 制作自定义类型的帖子
- excel - 添加/删除行而不使用通常的复制粘贴方法
- javascript - 使用永久地址让我的树莓派在线直播
- java - 为什么这些循环和散列操作需要 O(N) 时间复杂度?