[英]Preferred approach of implementing HTTP Post Method in Node.js
我發現了兩種方法來獲取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¶m2=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);
});
}
我認為第一種選擇是更常見的,因為需要較少的代碼,但您需要使用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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.