在Node.JS中将参数添加到HTTP POST请求

我已经知道如何使用Node.js发送一个简单的HTTP请求,如下所示:

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请求的主体中embedded参数,以及如何从接收器模块中捕获它们。

你介意使用请求库吗? 发送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 }); 

请求库也有一个在request.post方法中发布的快捷方式,在这个方法中,你传递url来发送一个post请求以及发送到那个url的数据。

根据评论编辑

要“捕捉”一个post请求,最好是使用某种框架。 由于快递是最stream行的一个,我会举一个快递的例子。 如果您不熟悉快递,我build议您阅读作者自己的入门指南 。

所有你需要做的是创build一个后路由,callback函数将包含发布到该url的数据

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