tank-http-client.js 一个支持链式调用的node http客户端

什么是 HTTP 客户端?

HTTP 客户端是一种用于发送 HTTP 请求和接收 HTTP 响应的工具。它们通常用于 Web 开发中,用于与 Web 服务器进行通信。

仓库地址

https://github.com/curry-trooper/tank-http-client.js

中文文档

https://github.com/curry-trooper/tank-http-client.js/blob/main/README_zh.md

安装

npm install tank-http-client.js

tank-http-client.js 的主要功能和特点

tank-http-client.js 是一个基于 needle.js 的 HTTP 客户端,只支持 Node.js 环境。它支持链式调用,单元测试和文档。以下是一些它的主要特点:

特性

支持链式调用 支持多种 HTTP 方法,如 GET、POST、PATCH、PUT、DELETE 等 支持设置请求头和请求体 支持设置超时时间 支持 Promise API 支持单元测试 更多的代码示例 以下是一些使用 tank-http-client.js 的代码示例:


//设置基础URL地址 
thc.setBaseUrl("http://localhost:3008")
//get 请求 链式调用
thc.get("/test")
   .query({id: 1})
   .send()
   .then((res) => {
       console.log(res)
   }).catch(err => {
   console.error(err)
});
//输出 ->{code: 200, method: 'GET', data: 'get_test', search: '1'}
//await  链式调用
async () => {
   const res = await thc.get("/test")
       .query({id: 1})
       .send()
   console.log(res)
}
//输出 ->{code: 200, method: 'GET', data: 'get_test', search: '1'}

链式调用的优点

链式调用是一种编程模式,它允许你在一行代码中完成多个操作。使用链式调用可以使代码更加简洁和易读。以下是一个使用链式调用的示例:

//use header
thc.get("/test").query({id: 1}).header({token: "token_8899"}).header("useAuth", true).send().then((res) => {
   //res:{code: 200, method: 'GET', data: 'get_test', search: '1',headerToken: "token_8899",useAuth:"true"}
})

//expressjs 
app.get('/test', function (req, res) {
   res.json({
       code: 200,
       method: req.method,
       data: "get_test",
       search: req.query["id"],
       headerToken: req.header("token"),
       useAuth: req.header("useAuth")
   })
})

PS

  • tank-http-client.js 是本人对needle.js 进行了二次封装,可靠性可以保证,这里提高了易用性,简化了开发流程,推荐大家使用
  • 此文章部分由ai生成,可能有误,请仔细斟读
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章