node.js - http with base64
本问题已经有最佳答案,请猛点这里访问。
我是node.js新手,一直在尝试实现base64编码。我的服务器似乎没有接收/处理base64消息。代码如下:
服务器:
1 2 3 4 5 6 7 8 9 10 11 | 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/'); |
客户:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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(); |
知道我做错了什么吗?
我想出了一个解决办法。我注意到在使用
这些精确的代码片段在本地主机上进行了测试:
客户:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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(); |
服务器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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/'); |
除了这些之外,我还注意到了代码中的这些错误。
1 2 3 | req.on('data',function(b) { var content = new Buffer(b, 'base64').toString('utf8') }); |
注意,在这种情况下,
这是您收集数据的方式:
1 2 3 4 5 6 7 | var content = ''; req.on('data', function(b) { content += b; }); req.on('end', function() { //do something with content }); |