Nestjs 请求别的服务地址获取Token

349 阅读1分钟

在 NestJS 中,你可以使用 HttpModule 来发送 HTTP 请求,并从另一个服务获取 token。下面是一个如何实现的示例:

  1. 安装依赖:确保你已经安装了 @nestjs/axios 包,因为我们将使用 HttpService 来发送 HTTP 请求。

    npm install @nestjs/axios
    
  2. 导入 HttpModule:在你的模块中导入 HttpModule

    import { Module } from '@nestjs/common';
    import { HttpModule } from '@nestjs/axios';
    import { YourService } from './your.service';
    
    @Module({
      imports: [HttpModule],
      providers: [YourService],
    })
    export class YourModule {}
    
  3. 使用 HttpService 获取 Token:在你的服务中使用 HttpService 发送请求获取 token。

    import { Injectable } from '@nestjs/common';
    import { HttpService } from '@nestjs/axios';
    import { firstValueFrom } from 'rxjs';
    
    @Injectable()
    export class YourService {
      constructor(private readonly httpService: HttpService) {}
    
      async getToken(): Promise<string> {
        const url = 'https://example.com/api/token'; // 替换为实际的服务地址
        const body = {
          client_id: 'your-client-id', // 替换为实际的 client_id
          client_secret: 'your-client-secret', // 替换为实际的 client_secret
          grant_type: 'client_credentials', // 替换为实际的 grant_type
        };
    
        const response = await firstValueFrom(
          this.httpService.post(url, body)
        );
    
        return response.data.access_token; // 根据实际返回结构提取 token
      }
    }
    
  4. 调用 getToken 方法:在需要获取 token 的地方调用 getToken 方法。

    import { Controller, Get } from '@nestjs/common';
    import { YourService } from './your.service';
    
    @Controller('your-controller')
    export class YourController {
      constructor(private readonly yourService: YourService) {}
    
      @Get('fetch-token')
      async fetchToken(): Promise<string> {
        const token = await this.yourService.getToken();
        return token;
      }
    }
    

这样,你就可以通过向另一个服务发送请求获取 token 了。你可以根据需要调整请求的 URL、请求体或返回数据的解析方式。