【问题标题】:node.js - http with base64 [duplicate]node.js - 带有 base64 的 http [重复]
【发布时间】:2013-05-21 06:59:45
【问题描述】:

我是一个 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();

任何想法我做错了什么?

【问题讨论】:

标签: javascript node.js


【解决方案1】:

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

这些确切的 sn-ps 已在 localhost 进行了测试:

客户:

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
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 2012-02-06
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    相关资源
    最近更新 更多