NodeJs使用Bent发送请求和Form表单提交
关于nodejs的APIClient,大名鼎鼎的request模块已停止维护,并推荐使用更为简洁的bent模块。下面看一下bent的用法:(官方)
第一种形式:
const bent = require('bent') const getJSON = bent('json') const getBuffer = bent('buffer') let obj = await getJSON('http://site.com/json.api') let buffer = await getBuffer('http://site.com/image.png')
支持:string、buffer、json ,3种类型
第二种形式:
const post = bent('http://localhost:3000/', 'POST', 'json', 200);
const response = await post('cars/new', {name: 'bmw', wheels: 4});
第三种形式:
const bent = require('bent') const getStream = bent('http://site.com') let stream = await getStream('/json.api') // status code stream.status // 200 stream.statusCode // 200 // optionally decode const obj = await stream.json() // or const str = await stream.text()
以第二种形式为例发送post请求默认为提交json对象,倘若要提交form表单怎么办。这时我们需要借助另一个模块来实现form表单编码,并将请求头设置为“application/x-www-form-urlencoded”即可。
首先依赖并引用form-urlencoded模块:
npm install form-urlencoded --save
const formurlencoded = require('form-urlencoded');
使用示例如下:
let headers = {}; headers['content-type'] = 'application/x-www-form-urlencoded'; return post(uri, formurlencoded(param), headers);
这时提交的就是form表单
致读者:感谢你阅读本文,请随手点击右下角的推荐或分享,谢谢!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?