You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NestJS Axios发送GET请求时出现“Cannot read properties of undefined (reading 'emit')”错误

NestJS HttpService 请求触发"Cannot read properties of undefined (reading 'emit')"错误解决

问题背景

项目依赖版本:

  • @nestjs/common: ^9.4.0
  • @nestjs/axios: ^2.0.0
  • axios: ^1.3.6
  • follow-redirects: ^1.15.2

严格按照官方文档实现geo.module.ts与GeoService,调用this.httpService.get()发送任意GET请求时,均抛出如下错误:

[Nest] 424  - 2023. 04. 27. 7:49:48   ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'emit')
TypeError: Cannot read properties of undefined (reading 'emit')
    at Object.eventHandlers.<computed> [as abort] (C:\somewhere\node_modules\follow-redirects\index.js:14:24)
    at TransformOperationExecutor.transform (C:\somewhere\node_modules\src\TransformOperationExecutor.ts:207:39)
    at TransformOperationExecutor.transform (C:\somewhere\node_modules\src\TransformOperationExecutor.ts:327:31)
    at TransformOperationExecutor.transform (C:\somewhere\node_modules\src\TransformOperationExecutor.ts:327:31)
    at TransformOperationExecutor.transform (C:\somewhere\node_modules\src\TransformOperationExecutor.ts:327:31)

已尝试方案均无效:版本兼容性检查、降级follow-redirects/axios、直接使用原生axios、设置maxRedirects:0、切换HTTP/HTTPS协议。

解决方案

1. 仅返回响应数据而非完整响应对象

axios响应对象包含事件发射器等不可序列化的内部属性,class-transformer在序列化时会触发错误。修改服务代码,只提取response.data返回:

import { lastValueFrom } from 'rxjs';
import { HttpService } from '@nestjs/axios';

@Injectable()
export class GeoService {
  constructor(private readonly httpService: HttpService) {}

  async fetchGeoData() {
    const response$ = this.httpService.get('目标URL');
    const response = await lastValueFrom(response$);
    // 仅返回业务数据,避免序列化整个响应对象
    return response.data;
  }
}

2. 配置class-transformer排除冗余属性

若必须返回完整响应,通过ClassSerializerInterceptor和装饰器排除不可序列化的属性:

  • 在DTO类中标记需要保留的字段,用@Exclude()排除其他属性:
import { Exclude, Expose } from 'class-transformer';

export class GeoResponseDto {
  @Expose()
  data: any; // 替换为你的实际数据类型

  @Expose()
  status: number;

  @Exclude()
  headers: any; // 排除包含事件发射器的headers等属性
}
  • 在模块中注册序列化拦截器,并设置全局转换选项:
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
import { ClassSerializerInterceptor } from '@nestjs/common';
import { ValidationPipe } from '@nestjs/common';

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: ClassSerializerInterceptor,
    },
    {
      provide: APP_PIPE,
      useValue: new ValidationPipe({
        transform: true,
        transformOptions: {
          excludeExtraneousValues: true, // 自动排除未标记@Expose的属性
        },
      }),
    },
  ],
})
export class GeoModule {}

3. 避免对axios响应实例执行转换操作

检查代码中是否存在对完整axios响应对象调用plainToInstance等class-transformer方法的情况,此类操作会尝试序列化内部事件属性。确保仅对response.data执行转换:

// 错误示例:直接转换完整响应对象
const dto = plainToInstance(GeoResponseDto, response);

// 正确示例:仅转换响应数据
const dto = plainToInstance(GeoResponseDto, response.data);

问题根源

错误栈中的TransformOperationExecutor来自class-transformer库,说明序列化流程中尝试访问follow-redirects内部的eventHandlers.emit方法,但该属性因axios响应对象的内部结构无法被正常序列化,最终触发undefined读取错误。本质是axios响应包含不可序列化的事件相关属性,class-transformer无法处理。

内容的提问来源于stack exchange,提问作者Adam Eros

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:42:05