nestjs intercept and modify outgoing http request

2019-08-07 14:58发布

问题:

So I'm likely missing something or doing something wrong. I have a NestJS application that is trying to make an http request to an external API. I'd like to be able to intercept this outgoing request and modify headers on it before executing it.

I've tried using Interceptors to no avail, the incoming http requests get intercepted but not the outgoing. Any suggestions or help would be greatly appreciated.

回答1:

Let's first deal with

I've tried using Interceptors to no avail, the incoming http requests get intercepted but not the outgoing.

According to the documentation https://docs.nestjs.com/interceptors it should be totally possible to intercept the response.

@Injectable()
export class TransformHeadersInterceptor implements NestInterceptor {
  intercept(
    context: ExecutionContext,
    call$: Observable<any>,
  ): Observable<any> {
    // Get request headers, e.g.
    const userAgent = context.switchToHttp().getRequest().headers['user-agent'];

    // Not sure if headers are writeable like this, give it a try
    context.switchToHttp().getResponse().headers['x-api-key'] = 'pretty secure';

    return call$;
  }
}

If you want to manipulate headers based on the the response data. You could tap into the data like so:

return call$.pipe(map(data => {
    // Your code here
    return data;
}));

I have some thoughts on:

I have a NestJS application that is trying to make an http request to an external API. I'd like to be able to intercept this outgoing request and modify headers on it before executing it.

So I think there two use cases. First, you have a set of default headers, that are assigned to the http client initially and send with each request. E.g.:

import { HTTP_TOKEN } from './constants';
import * as http from 'request-promise-native';

export const httpProviders: any = [
  {
    provide: HTTP_TOKEN,
    useFactory: () => {
      return http.defaults({
        headers: {
          'Accept': 'application/json',
          'Content-type': 'application/json',
          'User-agent': 'my-