我正在nodejs中构建应用程序,在该应用程序中,我必须通过点击HTTPS端点来显示数据。我正在使用Swagger UI来显示数据。我收到以下错误
Converting circular structure to JSON +1169ms
TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at stringify (node_modules/express/lib/response.js:1123:12)
at ServerResponse.json (node_modules/express/lib/response.js:260:14)
at ExpressAdapter.reply (node_modules/@nestjs/platform-express/adapters/express-adapter.js:23:57)
at RouterResponseController.apply (node_modules/@nestjs/core/router/router-response-controller.js:10:36)
at @nestjs/core/router/router-execution-context.js:163:48
at process._tickCallback (internal/process/next_tick.js:68:7)
即使我的代码中包含not used JSON.stringfy
,也是如此。如何解决此错误?
这是我的controller.ts代码
import { Observable } from 'rxjs';
@Controller('/service/api/message')
export class MessageController {
source: string;
productCode: string;
vehicleType: string;
constructor(private messageService: MessageService) {}
@Post()
@ApiUseTags('processor-dispatcher')
@ApiOperation({ title: 'Generate product message for the SNS topics' })
async generateMessage(@Body() productEvent: ProductEvent) {
return this.messageService
.getData(this.source, this.productCode, this.vehicleType)
.subscribe(res => {
console.log(res);
});
}
}
这是我的服务。
import Axios, { AxiosResponse } from 'axios';
@Injectable()
export class MessageService {
constructor(private readonly httpService: HttpService) {}
configEndPoint: string =
'https:www.xyz.com';
getData(
source: string,
productCode: string,
vehicleType: string,
): Observable<any> {
return this.httpService.get(this.configEndPoint, { validateStatus: null });
}
}
答案 0 :(得分:1)
您不应该subscribing
到可观察对象,NestJS将在后台进行处理,只需将未订阅的可观察对象返回给控制器,然后由Nest进行处理。
即使您没有使用它,也收到JSON.stringify
错误的原因是因为express
在其{{1 }} 方法。 send
类型(AxiosResponse
返回的内容)具有自身的循环引用,因此您无需发送完整的响应(无论如何都返回整个响应,这是一个不好的做法,过多的数据) 。您可以做的是在HttpService
中使用map
运算符来映射要发送回的部分资源。例子
pipe
这将获得@Injectable()
export class MessageService {
constructor(private readonly httpService: HttpService) {}
configEndPoint: string =
'https:www.xyz.com';
getData(
source: string,
productCode: string,
vehicleType: string,
): Observable<any> {
return this.httpService.get(this.configEndPoint, { validateStatus: null }).pipe(
map(res => res.data)
);
}
}
的{{1}}属性,并只允许将其发送回去。