首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Nestjs使用axios

Nestjs使用axios
EN

Stack Overflow用户
提问于 2018-10-18 00:25:40
回答 3查看 30.2K关注 0票数 21

这个简单的演示有一个错误

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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-10-18 06:32:00

您不能只返回整个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;
}
票数 34
EN

Stack Overflow用户

发布于 2018-10-18 06:20:17

正如您在示例中所写的,get方法返回AxiosResponse<>并包含循环引用。所以如果你想代理webservice https://api.github.com/users/januwA,你应该返回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));
  }
}
票数 1
EN

Stack Overflow用户

发布于 2018-10-18 22:22:00

您必须确保将响应作为JSON处理,您可以将其作为promise返回并获取数据,使用两者之一,或者使用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*/)
      }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52859515

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档