nestjs 发起请求 axios

发布于:2025-09-04 ⋅ 阅读:(19) ⋅ 点赞:(0)

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: 8080
    logger:
        # 项目日志存储路径,相对路径(相对本项目根目录)或绝对路径
        dir: '../logs'
    # 文件相关
    file:
        # 是否为本地文件服务或cos
        isLocal: true
        # location 文件上传后存储目录,相对路径(相对本项目根目录)或绝对路径
        location: '../upload'
        # 文件服务器地址,这是开发环境的配置 生产环境请自行配置成可访问域名
        domain: 'http://localhost:8080'
        # 文件虚拟路径, 必须以 / 开头, 如 http://localhost:8080/profile/****.jpg  , 如果不需要则 设置 ''
        serveRoot: '/profile'
        # 文件大小限制,单位M
        maxSize: 10
# 腾讯云cos配置
cos:
    secretId: ''
    secretKey: ''
    bucket: ''
    region: ''
    domain: ''
    location: ''
# 数据库配置
db:
    mysql:
        host: '127.0.0.1'
        username: 'root'
        password: '123456789'
        database: 'nestjs'
        port: 3306
        charset: 'utf8mb4'
        logger: 'file'
        logging: true
        multipleStatements: true
        dropSchema: false
        synchronize: false
        supportBigNumbers: true
        bigNumberStrings: true
    oracle:
        host: '192.168.20.171'
        port: 1521
        username: '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: 5000
  maxRedirects: 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


网站公告

今日签到

点亮在社区的每一天
去签到