HTTP 模块
Axios 是功能丰富的 HTTP 客户端包,被广泛使用。 Nest 封装了 Axios 并通过内置的 HttpModule 将其公开。 HttpModule 导出 HttpService 类,它公开了基于 Axios 的方法来执行 HTTP 请求。 该库还将生成的 HTTP 响应转换为 Observables。
安装
yarn add @nestjs/axios axios
HttpModule和HttpService是从@nestjs/axios包导入的。
import { HttpModule } from '@nestjs/axios'
HttpModule.register({
timeout:10000
}),
使用service
private readonly httpService: HttpService,
使用
import { Body, Controller, Get, Query, Post } from '@nestjs/common';
import { AppService } from './app.service';
import { Public } from './auth/public.guard';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs'
@Controller()
@Public()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly httpService: HttpService,
) {}
@Get('axios')
async testAxios(){
const data = this.httpService.get('https://m.maoyan.com/ajax/movieOnInfoList')
console.log(data)
return data
}
}
执行报错
这是因为由于 HttpService 方法的返回值是一个 Observable,我们可以使用 rxjs - firstValueFrom 或 lastValueFrom 以 promise 的形式检索请求的数据。
完整示例
import { Body, Controller, Get, Query, Post } from '@nestjs/common';
import { AppService } from './app.service';
import { Public } from './auth/public.guard';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom,catchError } from 'rxjs'
import { AxiosError } from 'axios'
import { response } from 'express';
@Controller()
@Public()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly httpService: HttpService,
) {}
@Get('axios')
async testAxios(){
const { data } = await firstValueFrom(this.httpService.get('https://m.maoyan.com/ajax/movieOnInfoList').pipe(response=>response))
console.log(data)
return data
}
}