nestjs 中使用HttpService请求第三方接口

您所在的位置:网站首页 nest怎么记 nestjs 中使用HttpService请求第三方接口

nestjs 中使用HttpService请求第三方接口

2024-07-15 02:23:04| 来源: 网络整理| 查看: 265

今天,把博客后端从nest8升级nest9之后,项目中直接使用axios请求第三方接口时,发现运行报错axios.get//undefind。 nest9中http请求需要用到HttpService来操作。HttpService是axios和rxjs组成的模块。rxjs结合http请求不熟悉,遇到了许多坑记录一下。

基本使用 import { HttpService } from '@nestjs/axios'; import { catchError, map } from 'rxjs/operators'; export class ResourcesService { constructor( @InjectRepository(File) private readonly fileRepository: Repository, private readonly httpService: HttpService, ) {} getImg(n = '1') { const res: any = this.httpService .get('http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=' + n) .pipe(map((res) => res.data)); // console.log(res); // 这里直接打印不出来数据格式的,都是映射函数,需要用subscribe观察 // res.subscribe((val) => console.log(val));// 订阅观察了,就可以打印出来 return res; } } 多个嵌套请求

复杂的嵌套请求的话,可以把每个请求都封装成promise来结合async/await使用(这里是封装成单个promise)。简单嵌套请求的话,可以使用rxjs的pipe和mergeMap配合使用。

1.封装成单个promise

import { HttpException, Injectable } from '@nestjs/common'; import { HttpService } from '@nestjs/axios'; import { Repository } from 'typeorm'; import { File } from './resources.entity'; import { InjectRepository } from '@nestjs/typeorm'; import { catchError, map } from 'rxjs/operators'; @Injectable() export class ResourcesService { constructor( @InjectRepository(File) private readonly fileRepository: Repository, private readonly httpService: HttpService, ) {} refresh_token = ''; access_token = ''; async baiDuTongJi(query) { // 请求数据 let data: any = await this.getDaiDuTongJiData(query); // console.log('data1', data); // token 过期 刷新token if (data.error_code === 110 || data.error_code === 111) { await this.refreshAccessToken(); // 重新请求数据 data = await this.getDaiDuTongJiData(query); // console.log('data2', data); } return data; } // 刷新 统计 access_token refreshAccessToken() { return new Promise((resolve) => { this.httpService .get(`http://openapi.baidu.com/oauth/2.0/token`, { params: { grant_type: 'refresh_token', refresh_token: this.refresh_token, client_id: '', // apikey client_secret: '', // SecretKey }, }) .pipe( map((res) => res.data), catchError((e) => { throw new HttpException(`刷新access_token错误`, 400); }), ) .subscribe((data) => { this.access_token = data.access_token; this.refresh_token = data.refresh_token; resolve(data); }); }); } // 获取统计数据 getDaiDuTongJiData(query) { return new Promise((resolve) => { const { url, ...otherParams /* 除了url其他组合成一个对象 */ } = query; this.httpService .get(`https://openapi.baidu.com${url}`, { params: { ...otherParams, access_token: this.access_token, }, }) .pipe(map((res) => res.data)) .subscribe((data) => resolve(data)); }); } }

2.使用rxjs内置的mergeMap mergeMap 操作符用于从内部的 Observable 对象中获取值,然后返回给父级流对象。

import { of } from "rxjs"; import { mergeMap } from "rxjs/operators"; const source$ = of("Hello"); const example$ = source$.pipe(mergeMap(val => of(`${val} World!`))); const subscribe = example$.subscribe(val => console.log(val));

3.rxjs的正确用法应该不是封装成promise的,这里是取巧实现了嵌套(修改参数之后)请求

参考RxJS 处理多个Http请求



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭