2014-03-06 197 views
1

我知道派如何使用Node.js作爲遵循一個簡單的HTTP請求的方式:添加參數HTTP POST請求的node.js

var http = require('http'); 

var options = { 
    host: 'example.com', 
    port: 80, 
    path: '/foo.html' 
}; 

http.get(options, function(resp){ 
    resp.on('data', function(chunk){ 
    //do something with chunk 
    }); 
}).on("error", function(e){ 
    console.log("Got error: " + e.message); 
}); 

我想知道如何在嵌入參數POST請求的主體以及如何從接收器模塊中捕獲它們。

+1

如果你是新來這個,甚至不嘗試做到這一點'http'代碼模塊,而不是像'express'或其他模塊那樣更友好的框架。 – Gntem

回答

6

你介意使用request library。發送POST請求變得簡單

var options = { 
url: 'https://someurl.com', 
'method': 'POST', 
'body': {"key":"val"} 

}; 

request(options,function(error,response,body){ 
    //do what you want with this callback functon 
}); 

請求庫還具有在其中傳遞的網址,POST請求與數據一起發送到該URL request.post方法後的快捷方式。

編輯基於評論

「捕捉」 POST請求,如果你使用某種框架,這將是最好的。由於express是最流行的一個,我會舉一個快遞的例子。如果你不熟悉快遞,我建議作者自己閱讀getting started guide

所有你需要做的就是創建一個帖子路線和回調函數將包含發佈到該網址的數據

app.post('/name-of-route',function(req,res){ 
console.log(req.body); 
//req.body contains the post data that you posted to the url 
}); 
+0

這很棒,但如何在接收端捕獲這些身體參數? –