Nestjs 使用 axios

Nestjs using axios

This simple demo has an error 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');
  }
}

我该怎么办?

[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>)

nest i
common version : 5.1.0
core version   : 5.1.0

如您在示例中所写,get 方法 return AxiosResponse<> 并包含循环引用。 所以如果你想代理网络服务 https://api.github.com/users/januwA,你应该 return AxiosResponse.data :

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<any>{
    return this.httpClient.get('https://api.github.com/users/quen2404')
      .pipe(map(response => response.data));
  }
}

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

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

或者使用 Promises:

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

您必须确保将您的响应作为 JSON 处理,您可以 return 它作为承诺并获取数据,使用两者之一或 HttpService 或 axios

import { Get, Controller, HttpService } from '@nestjs/common';
@Controller()
export class AppController {
  constructor(private readonly http: HttpService) {}
  @Get()
      root(): {
        return this.http.get('https://api.github.com/users/quen2404')
        .toPromise()
        .then(res => res.data)
        .catch(err => /*handle error*/)
      }
}