我是一名 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();
你知道我做错了什么吗?
最佳答案
我想出了一个解决办法。我注意到在使用 req.write(data, 'base64');
时请求从未结束。相反,我创建了一个 Base64 编码的缓冲区,然后将其写入请求。
这些确切的片段已在本地主机上进行了测试:
客户:
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
});
关于javascript - node.js - 使用 base64 的 http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16755917/