当前位置: 首页 > news >正文

使用 typed-rest-client 进行 REST API 调用

typed-rest-client 是一个用于 Node.js 的库,它提供了一种类型安全的方式来与 RESTful API 进行交互。其主要功能包括:

安装 typed-rest-client

要使用 typed-rest-client,首先需要安装它,可以通过 npm 来安装:

$ npm install typed-rest-client

使用 typed-rest-client

这里假定有个 express 的 server 提供了两个 REST API,一个是获取用户列表,一个是获取用户信息。

index.ts

import express, { Express, Request, Response } from "express";const app: Express = express();
const port = process.env.PORT || 3000;app.get("/", (req: Request, res: Response) => {res.send("Express + TypeScript Server");
});app.get("/users", (req: Request, res: Response) => {const users = [{name: 'kongxx',password: 'password',email: 'kongxx@example.com'},{name: 'Mandy',password: 'password',email: 'mandy@example.com'}]res.json(users);
});app.get("/users/:id", (req: Request, res: Response) => {const user = {name: 'kongxx',password: 'password',email: 'kongxx@example.com'}res.json(user);
});app.listen(port, () => {console.log(`[server]: Server is running at http://localhost:${port}`);
});

下面是测试程序

test.ts

import {RestClient, IRestResponse} from 'typed-rest-client/RestClient';interface User {name: string;password: string;email: string;
}async function test() {const rc: RestClient = new RestClient('test', 'http://localhost:3000');const resUsers: IRestResponse<User[]> = await rc.get<User[]>('/users');console.log('get users ...');console.log('response: ', resUsers);console.log('statusCode: ', resUsers.statusCode);console.log('name: ', resUsers.result[0]?.name);console.log('email: ', resUsers.result[0]?.email);const resUser: IRestResponse<User> = await rc.get<User>('/users/1');console.log('get user ...');console.log('response: ', resUser);console.log('statusCode: ', resUser.statusCode);console.log('name: ', resUser.result?.name);console.log('email: ', resUser.result?.email);
}test();
  • 这里首先定义了一个 interface,描述了 REST API 返回使用的数据结构。
  • 调用 RestClientget 方法,传入 URL 和返回的数据类型,返回一个 IRestResponse 对象,IRestResponse 对象包含了 HTTP 响应的状态码、响应头和响应体。
  • 通过 statusCode 属性可以获取到 HTTP 响应的状态码。
  • 通过 headers 属性可以获取到 HTTP 响应头。
  • 通过 result 属性可以获取到响应体中的数据。

测试

首先启动express server。

$ npm run dev

运行测试程序

$ npm install -g typescript
$ tsc src/test.ts  && node src/test.jsget users ...
response:  {statusCode: 200,result: [{name: 'kongxx',password: 'password',email: 'kongxx@example.com'},{name: 'Mandy',password: 'password',email: 'mandy@example.com'}],headers: {'x-powered-by': 'Express','content-type': 'application/json; charset=utf-8','content-length': '137',etag: 'W/"89-50ejbxheoPkdk58Nm75VjrVs3YE"',date: 'Mon, 23 Sep 2024 01:01:04 GMT',connection: 'close'}
}
statusCode:  200
name:  kongxx
email:  kongxx@example.comget user ...
response:  {statusCode: 200,result: { name: 'kongxx', password: 'password', email: 'kongxx@example.com' },headers: {'x-powered-by': 'Express','content-type': 'application/json; charset=utf-8','content-length': '68',etag: 'W/"44-WML8FV1wUhoW//8kQuCB8B/FWaQ"',date: 'Mon, 23 Sep 2024 01:01:04 GMT',connection: 'close'}
}
statusCode:  200
name:  kongxx
email:  kongxx@example.com
http://www.lryc.cn/news/444980.html

相关文章:

  • 在Ubuntu 14.04上安装Solr的方法
  • LabVIEW提高开发效率技巧----使用LabVIEW工具
  • Pyspark dataframe基本内置方法(4)
  • 配置win10开电脑时显示可登录账号策略
  • 01-Mac OS系统如何下载安装Python解释器
  • 24 C 语言常用的字符串处理函数详解:strlen、strcat、strcpy、strcmp、strchr、strrchr、strstr、strtok
  • 数据驱动农业——农业中的大数据
  • 学习《分布式》必须清楚的《CAP理论》
  • navicat无法连接远程mysql数据库1130报错的解决方法
  • JetPack01- LifeCycle 监听Activity或Fragment的生命周期
  • OpenCSG推出StarShip SecScan:AI驱动的软件安全革新
  • 占道经营检测-目标检测数据集(包括VOC格式、YOLO格式)
  • 828华为云征文 | 云服务器Flexus X实例:RAG 开源项目 FastGPT 部署,玩转大模型
  • MySQL之基本查询(一)(insert || select)
  • 基于深度学习的多智能体协作
  • Nmap网络扫描器基础功能介绍
  • idea 编辑器常用插件集合
  • 如何优化Java商城系统的代码结构
  • 两数之和、三数之和、四数之和
  • 这几个方法轻松压缩ppt文件大小,操作起来很简单的压缩PPT方法
  • 【nvm管理多版本node】下载安装以及常见问题和解决方案
  • C++(学习)2024.9.23
  • 大数据处理从零开始————3.Hadoop伪分布式和分布式搭建
  • 跟着问题学12——GRU详解
  • 内核是如何接收网络包的
  • 计算机毕业设计之:基于微信小程序的电费缴费系统(源码+文档+讲解)
  • 【leetcode】环形链表、最长公共前缀
  • C#开发记录如何建立虚拟串口,进行串口通信,以及通信模板
  • 电源设计的艺术:从底层逻辑到工程实践
  • 软媒市场新探索:软文媒体自助发布,开启自助发稿新篇章