当前位置: 首页 > news >正文

nestjs 发起请求 axios

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

http://www.dtcms.com/a/361616.html

相关文章:

  • Onion-LO(已开源)——LIDAR里程计的统一框架
  • IO进程线程;标准io;文件IO;0901
  • PyTorch 实战(3)—— PyTorch vs. TensorFlow:深度学习框架的王者之争
  • 「日拱一码」075 机器学习——密度泛函理论DFT
  • 在 Unity 中调用腾讯云机器翻译
  • 命名空间级别应用 Pod 安全标准
  • 在 Ubuntu 24.04 LTS 上安装 SSH 并启用服务端实现远程连接
  • 别再刷屏console.log!JavaScript高级调试方法全攻略
  • Product Hunt 每日热榜 | 2025-08-30
  • C++“类吸血鬼幸存者”游戏制作的要点学习
  • IO_HW_9_1
  • 【零碎小知识点 】(二)Java基础与常用API编码实践
  • day2
  • 【STM32】中断软件分支处理( NVIC 和 GIC)
  • curl 介绍及使用教程
  • Kotlin 协程异步任务工具类:高效处理异步操作与超时控制
  • 构建共享新生态的智慧物流开源了
  • ClickHouse常见问题——ClickHouseKeeper配置listen_host后不生效
  • java设计模式一、单例模式
  • 查看LoRA 哪个适配器处于激活状态(67)
  • 【秋招笔试】2025.08.31小红书秋招笔试真题
  • 鸿蒙NEXT开发指南:Image、Video与Swiper组件全面解析
  • Mac idea 格式化代码快捷键
  • 用滑动窗口与线性回归将音频信号转换为“Token”序列:一种简单的音频特征编码方法
  • 若依vue自定义发布环境部署后所有菜单无法点击
  • Kubernetes一网络组件概述
  • 如何正确使用ChatGPT做数学建模比赛——数学建模AI使用技巧
  • Sqlsugar补充自定义模板
  • 环境搭建汇总
  • 在.NET标准库中进行数据验证的方法