安装bent
npm install bent
使用
const bent = require('bent');
//get请求
const getJSON = bent('json')
const getBuffer = bent('buffer')
let obj = await getJSON('https://***.cn/gais/**Api?name=2');
// let buffer = await getBuffer('http://site.com/image.png')
console.log(obj);
//post请求
const post = bent('http://***.com.cn/', 'POST', 'json', 200);
const response = await post('**/updateUser', {
"uuid": "******",
"available": 0
});
console.log(response);
其中bent(基本URL,HTTP方法,响应格式,状态码,标头,);
- HTTP方法:
'GET'
,'PUT'
,或任何其他ALLCAPS字符串将被用于设置HTTP方法。默认为'GET'
。 - 响应格式:可用格式
'string'
,'buffer'
以及'json'
。默认情况下,将返回响应对象/流,而不是解码后的响应。浏览器返回ArrayBuffer
而不是Buffer
。 - 状态码:任何数字都将被视为可接受的状态码。默认情况下,
200
是唯一可接受的状态代码。提供任何状态代码时,200
必须明确包括它们才能被接受。 - 标头:可以传递一个对象来设置请求标头。
- 基本URL:任何以'https:'或'http:'开头的字符串都被视为基本URL。后续查询仅需传递其余的URL字符串。
后续为异步请求响应(地址,请求体);
官网请查看:GitHub - mikeal/bent: Functional JS HTTP client (Node.js & Fetch) w/ async await
Form 表单格式参数请求
首先依赖并引用form-urlencoded模块:
npm install form-urlencoded --save
文件引入
const formurlencoded = require('form-urlencoded');
const requestUrl="http://localhost:1234";
const headers = { "content-type": "application/x-www-form-urlencoded" };
const params={
param1:"param1",
param2:"param2"
}
const post = bent(requestUrl, 'POST', 'json');
const response=await post('/test', formurlencoded(params), headers);