node.js模拟发送post请求一直返回400错误
求解
var http = require('http'); var querystring = require('querystring'); var contents = querystring.stringify({//序列化一个对象 phone: '18764285761', sn: '123456', mac:'test' }); var option = { method: 'post', host: 'edu.ishenka.com', prot: '80', path: '/frontend/web/index.php?r=/test/index', headers: {// 必选信息 "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8", "Content-Length":contents.length, // 请求长度, 通过上面计算得到 } }; var Dispose = function(response){ var body=''; response.on('data',function(data){ body += data; }); response.on('end',function(){ console.log(body); }); }; var req = http.request(option,Dispose); req.write(contents);//发送内容 req.end();
为什么不用request库?
https://www.npmjs.com/package/request
HTTP 400意为Bad Request,即参数错误。也许是你提供的参数并不符合后端的要求,你可以通过查看response获得更多信息