如何在Angular拦截器中向请求主体添加内容?

时间:2018-11-05 06:14:48

标签: javascript angular api interceptor

在这里,我可以修改标题,因为存在有关此功能的多个教程,但是:

@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对象,这样我的图像就消失了。

3 个答案:

答案 0 :(得分:7)

 req = req.clone({ 
  headers: req.headers.set('Accept', 'application/json'),
  body: {...req.body, hello: 'world' }});

像这样吗?

答案 1 :(得分:2)

这是我想要的,但我的情况是轻度起毛,但我遇到了一些并发症,可以解决一些额外的头痛问题。 这是我的最终实现:

  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;    
  }
}

Here's the editor link if any one else wants to check.

答案 2 :(得分:0)

这是一个可行的示例:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const clonedreq = req.clone({
            headers: req.headers.set("Authorization", "Bearer " + sessionStorage.getItem('userToken'))
        });
        return next.handle(clonedreq)
            .do(
            succ => {
                if(succ["status"] != null && succ["status"] != undefined){
                    this.loaderService.handleResponse('regular');
                }
             },
            err => {
                if (err.status === 401)
                    this.router.navigateByUrl('/Login');
                this.loaderService.handleResponse('regular');
            }
        );
}