nodejs http.request 参数格式之querystring

本文介绍了如何使用Node.js的http模块发送POST请求,并对比了使用JSON.stringify与querystring.stringify两种方式来构造请求体的区别。总结了POST请求参数传输的最佳实践。

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

测试代码


let show = (msg) => {
    console.log(msg)
}

const http = require('http');
const querystring = require('querystring');//注意:一个字符串的包

const postData = JSON.stringify({ //错误
    'license': '2016-8-20;50;50;50;50:0:2:1;yes;yes;50;50;50:0:0:0;50;3;1;0;50;50;yes;0;50\n'
});
//const postData = querystring.stringify({ //正确
//    'licnese': '2016-8-20;50;50;50;50:0:2:1;yes;yes;50;50;50:0:0:0;50;3;1;0;50;50;yes;0;50\n'
//});

const opt = {
    hostname: '192.168.1.1',
    port: 5000,
    path: '/api/test',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(postData)
    },
    timeout:10*1000
}

let req = http.request(opt, (res) => {
    // show(`res:${res}`);
    // show(`status:${res.statusCode}`)
    // show(`header:${res.headers}`)

   

    res.setEncoding('utf8');

    res.on('data', (result) => {
        show(`Response data:${result}`);
    })

    res.on('end', () => {
        show(`Request send finish`)
    })

   
})

req.setTimeout(opt.timeout,()=>{
    show(`request timeout...`)
    req.abort();// 超时则销毁请求 否则会程序会block住
})

req.on('error', (e) => {
    show(`problem with request:${e.message}`);
})


// 发送的参数 注意:必须是字符串
req.write(postData);
req.end();

上面例子用http.request像http://192.168.1.1:5000/api/test发送了一个post请求,并发送了一个license='2016-8-20;50;50;50;50:0:2:1;yes;yes;50;50;50:0:0:0;50;3;1;0;50;50;yes;0;50\n’的字符串数据

测试现象

1.用JSON.parse传输body数据,在服务器抓包接受的数据如下
JSON.parse传输参数
2.用querystring组件传输body数据,在服务器抓包的数据如下
querystring传输参数

总结:

  1. http.request post传参不能传输json对象,只接受字符串
  2. 字符串不能用JSON.stringify包装,否则会被当做key传输,服务器body接受为"key:value":""
  3. 用querystring包装参数,服务器可正确解析,服务器body接受为"key":“value”

❤️❤️❤️❤️❤️❤️❤️❤️❤️ 如果对您有用,一分一块都是爱 ❤️❤️❤️❤️❤️❤️❤️❤️❤️

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值