typescript NestJS 返回 HTTP 请求的结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50355670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:24:42  来源:igfitidea点击:

NestJS returning the result of an HTTP request

node.jstypescriptrxjsaxiosnestjs

提问by Francesco Borzi

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

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

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

按照NestJS HTTP 模块的示例,我所做的很简单:

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:

但是从客户端我得到 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)

TypeError: 在 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) 在 ExpressAdapter.reply (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules /@nestjs/core/adapters/express-adapter.js:41:52) 在 RouterResponseController.apply (/Users/francesco.borzi/sources/business-controller-rewrite/node_modules/@nestjs/core/router/router-response -controller.js:11:36) 在 process._tickCallback (internal/process/next_tick.js:182:7)

回答by Kamil My?liwiec

This issue comes from the axioslibrary. In order to fix that, you have to pull out the dataproperty:

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

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

回答by andyrue

The problem seems to stem from the fact that we are trying to return a Response object directly, and that is circular by nature. I'm not sure of the correct way to implement this, but I was able to get around it by using axios directly, unwrapping the promise and returning just the data.

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

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

UPDATE

更新

I realized I could just do the same thing to the Observable being returned from the httpServiceusing the new rxjs pipe method, so that's probably the better way to do it.

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

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

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