如何在Angular拦截器中向请求主体添加一些内容? [英] How to add something to the body of request inside an Angular interceptor?
问题描述
在这里,我可以修改标题,因为存在有关此功能的多个教程,但是:
Here I'm able to modify the header as there are multiple tutorials present regarding this feature but:
@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);
}
}
但是在我的情况下,有一个令牌需要添加请求主体而不是请求标头,因此有任何方法可以修改主体.
But in my case there's a token which I need to add the request body instead of the request header so is there any method to modify the body.
更新:对于一个简单的帖子请求,Mild Fuzz的方法非常有效但我想添加查询,如果它是一个GET请求,如果它是正文允许添加一个身体.最重要的是,当我尝试发送表格数据.
... request.body
删除表单数据并将其转换为JSON
对象,这样我的图像就消失了.
Update: Mild Fuzz's method is working great for a simple post request but I'll like to add to query if it's a GET request and body if it allows to add a body. And most importantly it broke when I tried to send a form data.
...request.body
removes the form data and transforms it to aJSON
object so my image is gone.
推荐答案
这是我想要的温和模糊测试",但在我的情况下,我遇到了一些复杂的问题,我可以用一些额外的头痛来解决.这是我的最终实现:
Thanks to Mild Fuzz that was what I wanted but in my case I had some complications which I was able to solve with some extra headache. Here's my final implementation:
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
console.log('Intercepted!', req);
const authService = this.injector.get(AuthService);
const reqCloned = this.handleBodyIn(req, localStorage.getItem('random_key'), 'random_key_added');
const copiedReq = reqCloned;
return next.handle(copiedReq);
}
handleBodyIn(req:HttpRequest<any>, tokenToAdd, tokenName) {
if (req.method.toLowerCase() === 'post') {
if (req.body instanceof FormData) {
req = req.clone({
body: req.body.append(tokenName, tokenToAdd)
})
} else {
const foo = {}; foo[tokenName] = tokenToAdd;
req = req.clone({
body: {...req.body, ...foo}
})
}
}
if (req.method.toLowerCase() === 'get') {
req = req.clone({
params: req.params.set(tokenName, tokenName)
});
}
return req;
}
}
这篇关于如何在Angular拦截器中向请求主体添加一些内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!