Nestjs 使用 axios

jan*_*w a 19 javascript node.js axios nestjs

这个简单的演示有一个错误 https://docs.nestjs.com/techniques/http-module

import { Get, Controller, HttpService } from '@nestjs/common';
import { AxiosResponse } from 'axios'
import { Observable } from 'rxjs'
@Controller()
export class AppController {
  constructor(private readonly http: HttpService) {}
  @Get()
  root(): Observable<AxiosResponse<any>>  {
    return this.http.get('https://api.github.com/users/januwA');
  }
}
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

[Nest] 7356   - 2018-10-18 00:08:59   [ExceptionsHandler] Converting circular structure to JSON +9852ms
TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
Run Code Online (Sandbox Code Playgroud)
nest i
common version : 5.1.0
core version   : 5.1.0
Run Code Online (Sandbox Code Playgroud)

Kim*_*ern 32

您不能只返回整个AxiosResponse对象,因为它无法序列化为 JSON。您很可能希望得到这样的响应data

@Get()
root() {
  return this.http.get('https://api.github.com/users/januwA').pipe(
    map(response => response.data)
  );
}
Run Code Online (Sandbox Code Playgroud)

或者使用Promises

@Get()
async root() {
  const response = await this.http.get('https://api.github.com/users/januwA').toPromise();
  return response.data;
}
Run Code Online (Sandbox Code Playgroud)

  • toPromise 将被弃用,请参阅文档 https://rxjs.dev/deprecations/to-promise (9认同)