node.js 调用外部接口 使用bent模块I(推荐)

博客介绍了JS中bent库的安装与使用,包括bent函数各参数(基本URL、HTTP方法、响应格式、状态码、标头)的含义和默认值,还提到后续为异步请求响应。此外,讲解了Form表单格式参数请求,需依赖并引用form-urlencoded模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装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(基本URLHTTP方法响应格式状态码,标头,);

  • 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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值