nestjs - 为什么它会给出 JSON.stringfy 错误,即使我没有使用它?
问题描述
我正在 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);
});
}
}
这是我的 service.ts
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 });
}
}
解决方案
您不应该subscribing
使用可观察对象,NestJS 会在后台处理它,只需将未订阅的可观察对象返回给控制器并让 Nest 处理它。
JSON.stringify
即使您没有使用它,您也会收到错误的原因是因为express
在其send
方法中使用了它。AxiosResponse
类型(返回的内容)HttpService
具有对自身的循环引用,因此您不需要发送完整的响应(无论如何返回整个响应是一种不好的做法,太多的额外数据)。您可以做的是map
在 a 中使用运算符pipe
来映射您想要发回的 res 的哪些部分。例子
@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)
);
}
}
这将获得 的data
属性AxiosResponse
并只允许将其发回。
推荐阅读
- android - 单击 DownloadManager 通知时转到前台
- dpdk - DPDK testpmd 最小流量
- symfony4 - Dropzone 和 webpack 安可
- bash - 运行 awk 命令并使用获取参数的脚本打印 $1
- csv - 合并多个 CSV 时 CSV 行尾的空格
- php - 如何在具有不同卷路径的 2 个独立容器上设置 php-fpm 和 nginx
- javascript - 在正则表达式 JavaScript 中允许变量
- azure - 使用 Microsft Graph/Azure AD 作为我的 API 的身份验证器来验证用户实体的逻辑是什么?
- linux - 使用“-sanitizer-coverage-prune-blocks=0”运行 honggfuzz 错误
- php - Zend 2 检查选择查询是否返回 NULL