nodejs http.request 参数格式之querystring

来源:互联网 发布:ibm大数据学院 编辑:程序博客网 时间:2024/05/16 05:39

测试代码

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”