1、下載
npm i --save @nestjs/axios axios
2、全局配置
import { HttpModule } from '@nestjs/axios';@Global()
@Module({imports: [HttpModule.registerAsync({inject: [ConfigService],useFactory: async (configService: ConfigService) => {return {timeout: configService.get('http.timeout'),maxRedirects: configService.get('http.maxRedirects'),};},}),],exports: [HttpModule],
})
全部全局模塊如下
import { Global, Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { HttpModule } from '@nestjs/axios'; import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm'; import configuration from '../../config/index'; import { JwtModule } from '@nestjs/jwt'; import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core'; import { JwtGuard } from 'src/utils/jwt/jwt-guard'; import { JwtStrategy } from 'src/utils/jwt/jwt-strategy'; import { WinstonService } from 'src/utils/logger/winston-service'; import { CatchLoggerFilter } from 'src/utils/logger/catch-logger-filter'; import { ResponseLoggerInterceptor } from 'src/utils/logger/response-logger-interceptor'; import { RedisModule } from '@nestjs-modules/ioredis'; import { RequirePermissionGuard } from 'src/utils/premission/require-premission.guard'; @Global() @Module({imports: [ConfigModule.forRoot({isGlobal: true,load: [configuration],}),TypeOrmModule.forRootAsync({name:"default",inject: [ConfigService],useFactory: (configService: ConfigService) => {return {type: 'mysql',...configService.get('db.mysql'),timezone: '+08:00',// logger: 'advanced-console',entities: [__dirname + '/../**/*.entity.{js,ts}'],} as TypeOrmModuleOptions;},}),TypeOrmModule.forRootAsync({name: "oracle",inject: [ConfigService],useFactory: async (configService: ConfigService) => {return {type: 'oracle',...configService.get('db.oracle'),// logger: 'advanced-console',timezone: '+08:00',entities: [__dirname + '/../**/*.entity.{js,ts}'],} as TypeOrmModuleOptions;},}),HttpModule.registerAsync({inject: [ConfigService],useFactory: async (configService: ConfigService) => {return {timeout: configService.get('http.timeout'),maxRedirects: configService.get('http.maxRedirects'),};},}),RedisModule.forRootAsync({inject: [ConfigService],useFactory: (configService: ConfigService) => {return {type: "single",url: configService.get('redis.url'),};},}),JwtModule.registerAsync({inject: [ConfigService],global: true,useFactory: (configService: ConfigService) => {return {secret: configService.get('jwt.secretkey'),// signOptions: { expiresIn: configService.get('jwt.expiresin') },};},})],providers: [JwtStrategy,{provide: APP_GUARD,useFactory: (configService: ConfigService) => {return new JwtGuard(configService);},inject: [ConfigService],},{provide: APP_GUARD,useClass: RequirePermissionGuard},{provide: WinstonService,inject: [ConfigService],useFactory: (configService: ConfigService) => {return new WinstonService(configService);}},{provide: APP_FILTER,useClass: CatchLoggerFilter},{provide: APP_INTERCEPTOR,useClass: ResponseLoggerInterceptor}],exports: [WinstonService,HttpModule], }) export class ShareModule { }
3、使用
import { Injectable } from "@nestjs/common";
import { HttpService } from "@nestjs/axios";
import { firstValueFrom } from "rxjs";@Injectable()
export class TestService {constructor(private readonly httpService: HttpService,) { }async getTest() {const observable = this.httpService.get('https://api.github.com/users/yangxiaodong');// 請求成功后使用firstValueFrom方法獲取結果const response = await firstValueFrom(observable);return response.data}
}
# 開發環境配置
env: 'development'
app:prefix: 'api'port: 8080logger:# 項目日志存儲路徑,相對路徑(相對本項目根目錄)或絕對路徑dir: '../logs'# 文件相關file:# 是否為本地文件服務或cosisLocal: true# location 文件上傳后存儲目錄,相對路徑(相對本項目根目錄)或絕對路徑location: '../upload'# 文件服務器地址,這是開發環境的配置 生產環境請自行配置成可訪問域名domain: 'http://localhost:8080'# 文件虛擬路徑, 必須以 / 開頭, 如 http://localhost:8080/profile/****.jpg , 如果不需要則 設置 ''serveRoot: '/profile'# 文件大小限制,單位MmaxSize: 10
# 騰訊云cos配置
cos:secretId: ''secretKey: ''bucket: ''region: ''domain: ''location: ''
# 數據庫配置
db:mysql:host: '127.0.0.1'username: 'root'password: '123456789'database: 'nestjs'port: 3306charset: 'utf8mb4'logger: 'file'logging: truemultipleStatements: truedropSchema: falsesynchronize: falsesupportBigNumbers: truebigNumberStrings: trueoracle:host: '192.168.20.171'port: 1521username: 'flyco_md'password: 'password'serviceName: 'maindb'synchronize: false# redis 配置
redis:url: 'redis://localhost:6379'password: 123456# jwt 配置
jwt:secretkey: 'you_secretkey'expiresin: '9999y'# axios配置
http:timeout: 5000maxRedirects: 5
# 權限 白名單配置
perm:router:whitelist:[{ path: '/api/auth/getCaptCha', method: 'GET' },{ path: '/api/auth/login', method: 'POST' },{ path: '/register', method: 'POST' },{ path: '/api/test/test', method: 'GET' },{ path: '/logout', method: 'POST' },{ path: '/perm/{id}', method: 'GET' },{ path: '/upload', method: 'POST' },]# 是否開啟驗證碼
sys:captchaEnabled: true