我在 NestJS 项目中使用的版本(我仅显示相关的包):
我尝试从一开始就遵循这里的文档:https://docs.nestjs.com/techniques/http-module
我创建了一个名为
geo.module.ts
的模块,它看起来像这样:
import { Module } from '@nestjs/common';
import { GeoService } from './geo.service';
import { GeoController } from './geo.controller';
import { HttpModule } from '@nestjs/axios';
@Module({
imports: [HttpModule.register({
timeout: 5000,
maxRedirects: 5,
})],
controllers: [GeoController],
providers: [GeoService]
})
export class GeoModule {}
创建了指向服务的控制器,这很好,这是服务:
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
@Injectable()
export class GeoService {
constructor(private readonly httpService: HttpService) {}
findSomething() {
return this.httpService.get('http://urldoesntmatter.something');
}
}
该函数运行,并抛出如下错误:
[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)
我输入的任何网址都会出现此错误。我已经用谷歌搜索了一整天,但无法解决这个问题,为什么会发生这种情况,似乎基于文档我没有错过任何东西。
我已经明白了。
基于 THIS 答案,我只是返回数据本身而不是整个 Axios 对象。这最终解决了问题。 (但这不在文档中。:))
所以更新后的代码将如下所示:
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
@Injectable()
export class GeoService {
constructor(private readonly httpService: HttpService) {}
findSomething() {
return this.httpService.get('http://urldoesntmatter.something').pipe(
map(response => response.data)
);
}
}
如果您已经查看并尝试解决问题,感谢您抽出时间。
这是来自 NestJs 文档的完整示例,对我有用:
由于 HttpService 方法的返回值是一个 Observable,我们可以使用 rxjs -firstValueFrom 或 lastValueFrom 以 Promise 的形式检索请求的数据。
import {
catchError,
firstValueFrom
} from 'rxjs';
@Injectable()
export class CatsService {
private readonly logger = new Logger(CatsService.name);
constructor(private readonly httpService: HttpService) {}
async findAll(): Promise < Cat[] > {
const {
data
} = await firstValueFrom(
this.httpService.get < Cat[] > ('http://localhost:3000/cats').pipe(
catchError((error: AxiosError) => {
this.logger.error(error.response.data);
throw 'An error happened!';
}),
),
);
return data;
}
}