网络请求
原创2026/3/5大约 1 分钟
Axios 是功能丰富的 HTTP 客户端包,被广泛使用。 Nest 封装了 Axios 并通过内置的 HttpModule 将其公开。 HttpModule 导出 HttpService 类,它公开了基于 Axios 的方法来执行 HTTP 请求。 该库还将生成的 HTTP 响应转换为 Observables。
要开始使用它,我们首先安装所需的依赖。
npm i --save @nestjs/axios axios安装过程完成后,要使用 HttpService,请先导入 HttpModule。
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { HttpModule } from '@nestjs/axios';
@Module({
imports: [
HttpModule.registerAsync({
useFactory: () => ({
timeout: 5000,
maxRedirects: 5,
}),
})
],
controllers: [UserController],
providers: [UserService]
})
export class UserModule { }使用
import { Controller, Get } from '@nestjs/common';
import { UserService } from './user.service';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
@Controller('user')
export class UserController {
constructor(
private readonly userService: UserService,
private readonly httpService: HttpService
) { }
@Get()
async findOne() {
const { data } = await firstValueFrom(
this.httpService.get('http://localhost:3000/user/v11').pipe(),
);
return data;
}
@Get("v1")
findOneV1() {
return { message: 'Hello world!' };
}
}此时,我们访问http://localhost:3000/user,拿到了message: 'Hello world!'的json对象
提示
由于 HttpService 方法的返回值是一个 Observable,我们可以使用 rxjs - firstValueFrom 或 lastValueFrom 以 promise 的形式检索请求的数据。
至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。