轶哥

📚 Having fun with AI Agent. Always learning.

Bent - 又一个JS HTTP Request Client
  •   更新:2020-08-16 19:32:34
  •   首发:2020-08-16 19:31:24
  •   教程
  •   4285

在JavaScript生态中,知名度最高的HTTP Request Library库是axios。有众多插件的HTTP请求库是superagent。各类请求库功能大体相同,用法和用途存在一些差异。今天介绍的HTTP Request Client库则是request的替代品bent

关于Request

自2020年2月11日起,request已被弃用。具体原因请见:https://github.com/request/request/issues/3142

Bent可以作为request在Node.js下简单高效的替代品。整个库只有三个文件,总代码不超过300行。

browser.js
core.js
nodejs.js

Bent用法示例

简单用法

const bent = require('bent')

// 定义使用GET方式请求并解析返回的JSON数据为JavaScript对象
const get = bent('GET', 'json')

// 定义使用POST方式请求并返回文本
const post = bent('POST', 'string')

const obj = await get('https://api.wyr.me/')
const res = await post('http://todo.sercretcore.cn/ip.php')

返回Buffer/ArrayBuffer

const bent = require('bent')

// 定义使用GET方式请求并返回作为Buffer
const getBuffer = bent('buffer')

const buffer = await getBuffer('https://data.sercretcore.cn/new_avatar.jpeg')

// 将返回的buffer内容转换为Base64
console.log(buffer.toString('base64'))

上述示例中,返回的Base64不带图片类型,可以通过header中的content-type获得文件类型,或参考《JS推测Base64图片类型》。

返回Stream

const bent = require('bent')

// bent是一个返回异步函数的函数
const request = bent()

; (async () => {
  const stream = await request('https://data.sercretcore.cn/new_avatar.jpeg')

  console.log(stream.status) // 200
  console.log(stream.statusCode) // 200

  const fs = require('fs')
  stream.pipe(fs.createWriteStream('avatar.jpeg'))
})()

上述示例中,我们将获取到的stream传输并保存到了文件中,相当于从URL下载一张图片并保存为文件。

Stream可以直接返回给客户端。

const bent = require('bent')

// bent是一个返回异步函数的函数
const request = bent()

; (async () => {
  const http = require('http')
  http.createServer(async function (req, res) {
    if (req.method === 'GET') {
      const stream = await request('https://data.sercretcore.cn/new_avatar.jpeg')
      res.writeHead(stream.statusCode, {
        "Content-type": stream.headers['content-type'],
        'Content-Length': stream.headers['content-length']
      })
      stream.pipe(res)
    }
  }).listen(80)
})()

运行以上代码,访问http://localhost,浏览器将显示一张图片。

bentavatar.png

更多用法请访问:https://github.com/mikeal/bent

总结

Axios非常适合VueReact等前端框架。

superagent适合爬虫、监控、模拟测试等业务。

需要兼容较老的浏览器可以选择jQueryajax()方法。

Node.js中,以上框架均可使用。由于目前Node.js对新版JS规范的支持较好,推荐简单高效的bent

打赏
交流区(2)
欢乐马

调试效率比之前快很多

2020年9月20日 09:02回复
轶哥

是的

2020年9月20日 09:04回复
尚未登陆
发布
  上一篇 (MacOS 同时使用内网和外网(双网卡同时联网))
下一篇 (PHP 获取客户端真实IP地址)  

评论回复提醒