大多数情况下,应用程序是要调用第三方 API 的,这时候就需要用到 http 客户端模块,在前端 Axios 是非常常见的,同样的,在 Nest 框架下也有像 Axios 一样的 http 客户端模块
# 安装 @nestjs/axios
安装也很方便
$ npm install @nestjs/axios -S |
# 使用 Http 客户端
安装完成之后,使用起来也很简单,只要在需要用到 http 客户端的模块下导入 HttpModule
, 就可以在当前模块下使用 HttpService
// app.modeule.ts | |
@Module({ | |
imports: [HttpModule,...], | |
providers: [...], | |
}) | |
export class AppModule {} |
// app.controller.ts | |
constructor( | |
private readonly appService: AppService, | |
private readonly httpClient: HttpService, | |
private readonly configService: ConfigService | |
) {} | |
@Get('mysql_host') | |
async getMysqlHost() { | |
const {host} = this.configService.get('database'); | |
const {data} = await this.httpClient.get(`http://${host}`).toPromise(); | |
return `${data} ${host}`; | |
} |
注意的一点是,所有 HttpService
的方法都返回一个包裹在 Observable
对象内的 AxiosResponse
.
可以使用 toPromise
拿到数据.