node.js – 带有base64的http

我是一个node.js新手卡住试图实现base64编码。 我的服务器似乎没有接收/处理base64消息。 代码如下:

服务器:

var http = require('http'); http.createServer(function (req, res) { req.on('data',function(b) { console.log("HEY!"); // <--- Never gets called var content = new Buffer(b, 'base64').toString('utf8') console.log("CLIENT SAID: "+content); var msg = JSON.parse(content); // do stuff and respond here... }); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); 

客户:

 var http = require('http'); var options = { hostname : 'localhost', port : 1337, method : 'POST' }; var req = http.request(options, function(res) { res.setEncoding('base64'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); // write data to request body var msg = {'name':'Fred','age':23}; var msgS = JSON.stringify(msg); req.write(msgS,'base64'); req.end(); 

任何想法我做错了什么?

我想出了一个解决scheme。 我注意到当使用req.write(data, 'base64'); 该请求永远不会结束。 我创build了一个base64编码的缓冲区,然后将其写入请求。

这些确切的片段被testinglocalhost:

客户:

 var http = require('http'); var options = { hostname: 'localhost', port: 1337, method: 'POST' }; var req = http.request(options, function (res) { res.setEncoding('base64'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); var msg = { 'name': 'Fred', 'age': 23 }; var msgS = JSON.stringify(msg); var buf = new Buffer(msgS, 'base64'); req.write(msgS); req.end(); 

服务器:

 var http = require('http'); http.createServer(function (req, res) { var content = ''; req.on('data', function (chunk) { content += chunk; }); req.on('end', function() { content = content.toString('base64'); console.log(content); //content returns {"name": "Fred","age": 23}; res.end(); }); }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); 

除了这些东西,我注意到你的代码中的这些错误。

 req.on('data',function(b) { var content = new Buffer(b, 'base64').toString('utf8') }); 

请注意,在这种情况下, b实际上已经是一个缓冲区。 你应该使用b.toString('base64'); 。 还要注意, b实际上只是数据的片段。 你应该收集b的数据,然后听end事件,最后做一些数据。 在你的情况与req.write(data, 'base64'); ,结局永远不会开火,导致挂断,而不是事件发生。

这是你如何收集数据:

 var content = ''; req.on('data', function(b) { content += b; }); req.on('end', function() { //do something with content });