nestjs调用第三方接口

后端服务经常要调用第三方接口,比如微信授权登录、支付、OSS文件上传等。

官方文档

安装依赖
npm i @nestjs/axios -S
封装接口请求方法

utils/http.service.ts

注意:调用接口返回的数据格式是Observable格式,无法直接获取内容,需要使用 rxjs 包提供的 lastValueFrom 方法转换数据格式为对象格式。

/**
 * 请求外部api
 * options: {
 *  method: get、post 请求方式,默认get
 *  url: '' 接口地址
 *  data: {} 请求参数
 * }
 */

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { lastValueFrom } from 'rxjs';
import { parseParam } from './utils';

@Injectable()
export class httpClint {
  constructor(private http: HttpService) {}

  // 远程接口请求
  async originApi(options: any) {
    let checkResultObservable; // 远程接口响应数据
    if (options.method === 'post') {
      // POST
      checkResultObservable = this.http.post(options.url, options.data || {});
    } else {
      // GET
      let url = options.url;
      if (options.data) {
        // 序列化参数
        url += '?' + parseParam(options.data);
      }
      checkResultObservable = this.http.get(url);
    }
    // lastValueFrom处理Observable格式数据,转换为对象格式
    const checkResult: any = await lastValueFrom(checkResultObservable);
    return checkResult.data;
  }
}
module.ts引用接口请求
// ...
import { httpClint } from '../utils/http.service';

@Module({
  // ...
  providers: [httpClint]
})
export class ApiModule {}
service.ts使用接口请求
import { Injectable } from '@nestjs/common';
import { httpClint } from '../utils/http.service';

@Injectable()
export class ApiService {
  constructor(private readonly httpClint: httpClint) {}

  // get请求
  async getOriginApi() {
    return this.httpClint.originApi({
      url: 'https://result.eolink.com/ahTwxH9f60798b38cfdb6dfe217802d36851c6642a4e197',
      data: {
        uri: 'huser/userinfo'
      }
    });
  }

  // post请求
  async postOriginApi() {
    return this.httpClint.originApi({
      method: 'post',
      url: 'https://result.eolink.com/3W53VaC109149cdb72d8b3e13e8841250f4db06d49c4bcd?uri=wxinfos/remind',
      data: {
        uri: 'wxinfos/remind'
      }
    });
  }
}
验证

在eolink配置一个远程测试接口

调用nest项目对应接口

  • 10
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值