本文介绍了如何向 Angular 拦截器内的请求正文添加内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

感谢 Mild Fuzz,这正是我想要的,但就我而言,我遇到了一些复杂的问题,但我能够解决一些额外的麻烦.这是我的最终实现:

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 拦截器内的请求正文添加内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:29