这个简单的演示有一个错误
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
发布于 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;
}
发布于 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));
}
}
发布于 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*/)
}
}
https://stackoverflow.com/questions/52859515
复制相似问题