为什么即使我没有使用它也会给JSON.stringfy错误?

问题描述 投票:0回答:1

我正在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);
      });
  }
}

这是我的服务。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 });

  }
}

nestjs stringify
1个回答
0
投票

您不应该将Observable视为subscribing,NestJS会在后台对其进行处理,只需将未订阅的Observable返回给控制器,然后由Nest对其进行处理。

即使未使用[[you,也出现JSON.stringify错误的原因,是因为express在其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) ); } }
这将获得dataAxiosResponse属性,并且只允许将其发送回去。
© www.soinside.com 2019 - 2024. All rights reserved.