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表单
致读者:感谢你阅读本文,请随手点击右下角的推荐或分享,谢谢!

浙公网安备 33010602011771号