首页 > 解决方案 > 为什么它会给出 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 });

  }
}

标签: nestjsstringify

解决方案


您不应该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并只允许将其发回。


推荐阅读