当前位置: 首页 > 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.xdnf.cn/news/1423207.html

相关文章:

  • 3-6〔OSCP ◈ 研记〕❘ WEB应用攻击▸WEB应用枚举B
  • 【STM32】状态机(State Machine)
  • 证明与激励:Walrus 可编程数据如何通过激励可用性证明获得安全性
  • SpringBoot学习日记 Day9:响应式编程新世界探索
  • 【跨境知识】密文面单
  • Linux常用命令行大全:14个核心指令详解+实战案例
  • 多线程——线程的休眠、中断和等待
  • Markdown 语法全面指南
  • Win10系统获取网络上行流量的三种方法
  • 五、导入现有模型
  • 01 2025最新VMware虚拟机下载教程
  • Unity项目基本风格/规范
  • Linux上perf工具的使用-基础采样
  • 命名空间级别应用 Pod 安全标准
  • 从组分到涌现:系统科学视域下结构、功能与层级的辨析及在人工智能中的应用
  • 安全等保复习笔记
  • 大模型 RAG 项目必看:技术架构拆解 + 实战步骤,新手也能快速上手
  • 内存管理 - 从虚拟到物理
  • Java全栈工程师面试实战:从基础到微服务的深度解析
  • CentOS10安装RabbitMQ
  • Spring Bean 生命周期中的 @PostConstruct 注解
  • NestJS 3 分钟搭好 MySQL + MongoDB,CRUD 复制粘贴直接运行
  • 【C++进阶篇】学习C++就看这篇--->多态超详解
  • 传统web项目,vue开发实践篇01
  • 微服务Docker-compose之若依部署
  • 视频提取文字用什么软件好?分享6款免费的视频转文字软件!
  • apipost 8.x 脚本循环调用接口
  • 云手机为什么会受到广泛关注?
  • 单链表的基本原理与实现
  • 深入掌握 Flask 配置管理:从基础到高级实战