NestJS 返回 HTTP 请求的结果

NestJS returning the result of an HTTP request

在我的 NestJS 应用程序中,我想 return http 调用的结果。

按照NestJS HTTP module的例子,我所做的只是:

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(...);
  }
}

但是从客户端我得到 500 并且服务器控制台显示:

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)

问题似乎源于我们试图直接 return 一个 Response 对象,而这本质上是循环的。我不确定实现这个的正确方法,但我能够通过直接使用 axios 来绕过它,解开承诺并 return 只处理数据。

@Post('login')
  async authenticateUser(@Body() LoginDto) {
    const params = JSON.stringify(LoginDto);

    return await axios.post('https://api.example.com/authenticate_user',
      params,
      {
        headers: {
          'Content-Type': 'application/json',
        },
      }).then((res) => {
          return res.data;
    });
}

更新

我意识到我可以使用新的 rxjs 管道方法对从 httpService 编辑的 Observable 做同样的事情,所以这可能是更好的方法。

@Post('login')
async authenticateUser(@Body() LoginDto) {
    const params = JSON.stringify(LoginDto);

    return this.httpService.post('https://api.example.com/authenticate_user',
      params,
      {
        headers: {
          'Content-Type': 'application/json',
        },
      }).pipe(map((res) => {
    return res.data;
  }));
}

这个问题来自 axios 库。为了解决这个问题,你必须拉出 data 属性:

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