我正在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 });
}
}
您不应该将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)
);
}
}
这将获得data
的AxiosResponse
属性,并且只允许将其发送回去。