How to add something to the body of request inside an Angular interceptor?

谁都会走 提交于 2020-12-28 07:06:49

问题


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.

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 a JSONobject so my image is gone.


回答1:


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

something like this?




回答2:


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

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




回答3:


Here's a working example:

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


来源:https://stackoverflow.com/questions/53149223/how-to-add-something-to-the-body-of-request-inside-an-angular-interceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!