在Node.js中实现HTTP Post方法的首选方法

我发现了两种方法来获取Node.js中的Post Body数据

下面是2个webservice Post方法,所以在Node.js中通过rest api从客户端获取数据时需要遵循的首选方法,或者是否有其他方法来读取post数据。

第一种方法

//http://localhost:1337/api/postparams1 //Content-Type: application/x-www-form-urlencoded //param1=complete+reference&param2=abcd+1234 function postparams1(req, res) { var result = { Url : req.originalUrl, Method : req.method, Param1 : req.body.param1, Param2 : req.body.param2 }; res.status(200).send(result); } 

第二种方法

 //http://localhost:1337/api/postparams2 //{ // "param1" : "param value 1", // "param2" : "param value 2" //} function postparams2(req, res) { var data = ''; req.setEncoding('utf8'); req.on('data', function (chunk) { data += chunk; console.log("In data : " + data); }); req.on('end', function () { console.log("In end : " + data); var newObj = JSON.parse(data); newObj.Url = req.originalUrl; newObj.Method = req.method, res.status(200).send(newObj); }); } 

我认为第一个选项更常见,因为需要更less的代码,但是您需要使用Express。

Express 3代码:

 app.use(express.bodyParser()); app.post('/', function(request, response){ console.log(request.body.param1); console.log(request.body.param2); }); 

Express 4代码:

 var bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.post('/', function(request, response){ console.log(request.body.param1); console.log(request.body.param2); }); 

在这里查看更多信息:

提取节点中的发布数据

  var req = https.get("url", function(response) { var str = '' response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { console.log(str); }); }); req.end(); req.on('error', function(e) { console.error(e); });