Nestjs using axios

后端 未结 3 1235
[愿得一人]
[愿得一人] 2021-02-05 19:56

This simple demo has an error https://docs.nestjs.com/techniques/http-module

import { Get, Controller, HttpService } fro         


        
相关标签:
3条回答
  • 2021-02-05 20:33

    You cannot just return the whole AxiosResponse object because it cannot be serialized to JSON. You most likely want to get the response data like this:

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

    or alternatively using Promises:

    @Get()
    async root() {
      const response = await this.http.get('https://api.github.com/users/januwA').toPromise();
      return response.data;
    }
    
    0 讨论(0)
  • 2021-02-05 20:43

    as you write in your example, get method return AxiosResponse<> and contains circular reference. So if you want to proxify webservice https://api.github.com/users/januwA, you should 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));
      }
    }
    
    0 讨论(0)
  • 2021-02-05 20:58

    You have to make sure to handle your responses as a JSON you can return it as a promise and get the data, use one of both or HttpService or axios

    import { Get, Controller, HttpService } from '@nestjs/common';
    @Controller()
    export class AppController {
      constructor(private readonly http: HttpService) {}
      @Get()
          root(): {
            return this.httpClient.get('https://api.github.com/users/quen2404')
            .toPromise()
            .then(res => res.data)
            .catch(err => /*handle error*/)
          }
    }
    
    0 讨论(0)
提交回复
热议问题