NestJS returning the result of an HTTP request

Francesco Borzi picture Francesco Borzi · May 15, 2018 · Viewed 23.8k times · Source

In my NestJS application I want to return the result of an http call.

Following the example of the NestJS HTTP module, what I'm doing is simply:

import { Controller, HttpService, Post } from '@nestjs/common';
import { AxiosResponse } from '@nestjs/common/http/interfaces/axios.interfaces';
import { Observable } from 'rxjs/internal/Observable';

@Controller('authenticate')
export class AuthController {

  constructor(private readonly httpService: HttpService) {}

  @Post()
  authenticate(): Observable<AxiosResponse<any>> {
    return this.httpService.post(...);
  }
}

However from the client I'm getting 500 and the server console is saying:

TypeError: Converting circular structure to JSON at JSON.stringify () at stringify (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules/express/lib/response.js:1119:12) at ServerResponse.json (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules/express/lib/response.js:260:14) at ExpressAdapter.reply (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules/@nestjs/core/adapters/express-adapter.js:41:52) at RouterResponseController.apply (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules/@nestjs/core/router/router-response-controller.js:11:36) at at process._tickCallback (internal/process/next_tick.js:182:7)

Answer

Kamil Myśliwiec picture Kamil Myśliwiec · May 16, 2018

This issue comes from the axios library. In order to fix that, you have to pull out the data property:

return this.httpService.post(...)
  .pipe(
    map(response => response.data),
  );