在这里,我可以修改标题,因为有多个关于此功能的教程,但是:
@Injectable()
export class MyFirstInterceptor implements HttpInterceptor {
constructor(private currentUserService: CurrentUserService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(JSON.stringify(req));
const token: string = this.currentUserService.token;
if (token) {
req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
}
if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}
req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
return next.handle(req);
}
}
但就我而言,有一个令牌需要添加请求正文而不是请求标头,因此是否有任何方法可以修改正文。
更新:Mild Fuzz 的方法对于简单的发布请求非常有效
但我想添加到查询(如果是 GET 请求)和正文(如果是)
允许添加主体。最重要的是,当我尝试时它坏了
发送表单数据。...request.body
删除表单数据并
将其转换为JSON
对象所以我的图像消失了。
req = req.clone({
headers: req.headers.set('Accept', 'application/json'),
body: {...req.body, hello: 'world' }});
像这样的东西?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)