如何发送来自node.js Express的POST请求?

有人可以告诉我从node.js Express发送post请求的最简单方法,包括如何传递和检索一些数据? 我期待类似于PHP中的cURL。

简单与请求库。

npm安装请求

 var request = require('request'); // Set the headers var headers = { 'User-Agent': 'Super Agent/0.0.1', 'Content-Type': 'application/x-www-form-urlencoded' } // Configure the request var options = { url: 'http://samwize.com', method: 'POST', headers: headers, form: {'key1': 'xxx', 'key2': 'yyy'} } // Start the request request(options, function (error, response, body) { if (!error && response.statusCode == 200) { // Print out the response body console.log(body) } }) 

以上代码将在主体中执行POST https:// localhost:8080 / with key1 = xxx&key2 = yyy。

正如这里所描述的一个post请求:

 var http = require('http'); var options = { host: 'www.host.com', path: '/', port: '80', method: 'POST' }; callback = function(response) { var str = '' response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { console.log(str); }); } var req = http.request(options, callback); //This is the data we are posting, it needs to be a string or a buffer req.write("data"); req.end(); 

我使用superagent ,这是jQuery的simliar。

这里是文档

和演示一样:

 var sa = require('superagent'); sa.post('url') .send({key: value}) .end(function(err, res) { //TODO }); 
 var request = require('request'); function updateClient(postData){ var clientServerOptions = { uri: 'http://'+clientHost+''+clientContext, body: JSON.stringify(postData), method: 'POST', headers: { 'Content-Type': 'application/json' } } request(clientServerOptions, function (error, response) { console.log(error,response.body); return; }); } 

为了这个工作,你的服务器必须是这样的:

 var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()) var port = 9000; app.post('/sample/put/data', function(req, res) { console.log('receiving data ...'); console.log('body is ',req.body); res.send(req.body); }); // start the server app.listen(port); console.log('Server started! At http://localhost:' + port);