Node.js中的HTTP POST不起作用

从nodejs我试图发布数据到另一个URL 127.0.0.1:3002(在文件poster.js),但是当我尝试访问它在服务器上的127.0.0.1:3002然后发布的数据不会来:

我的poster.js看起来像这样:

var http = require('http'); function post() { var options = { host : '127.0.0.1', port : 3002, path : '/note/', method : 'POST' }; var req = http.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); req.write("<some>xml</some>"); req.end(); } post(); 

和我的服务器代码在app.js是:

 var express=require('express'); app=express(); app.post('/note',function(req,res){ console.log(req.params); }) app.listen(3002); console.log('sweety dolly') 

我的服务器控制台显示:

 sweety dolly [] 

req.params显示[]这意味着它没有收到什么,而发送我发送XML

在两个不同的命令行中,我发射了两个不同的进程

  node app 

然后在下一个命令行

  node poster 

我究竟做错了什么????

你的客户端工作,但是当你POST ,默认情况下数据不会以服务器params显示(实际上,参数是路由信息)

由于您发布的是原始数据,因此您需要自己收集数据以使用它,例如通过use自己的简单身体分析器;

 var express=require('express'); app=express(); app.use(function(req, res, next) { var data = ''; req.setEncoding('utf8'); req.on('data', function(part) { // while there is incoming data, data += part; // collect parts in `data` variable }); req.on('end', function() { // when request is done, req.raw_body = data; // save collected data in req.body next(); }); }); app.post('/note',function(req,res){ console.log(req.raw_body); // use req.body that we set above here }) app.listen(3002); console.log('sweety dolly') 

编辑:如果你想要的数据作为参数,你需要改变客户端发布的数据作为查询string与数据的名称;

 var http = require('http'); var querystring = require('querystring'); function post() { var post_data = querystring.stringify({ xmldata: '<some>xml</some>' }) var options = { host : '127.0.0.1', port : 3002, path : '/note/', method : 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': post_data.length } }; var req = http.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); req.write(post_data); req.end(); } post(); 

然后你可以使用标准的bodyParserparam函数获取数据;

 var express=require('express'); app=express(); app.use(express.bodyParser()); app.post('/note',function(req,res){ console.log(req.param('xmldata')); }) app.listen(3002); console.log('sweety dolly')