2013-05-26 61 views
2

我是一個node.js新手堅持嘗試實現base64編碼。我的服務器似乎沒有收到/處理base64消息。下面的代碼:node.js - http與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(); 

任何想法我做錯了嗎?

+0

看看這個:http://stackoverflow.com/questions/6182315/how-to-do-base64-encoding-in-node -js –

回答

2

我想出了一個修復。我注意到在使用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 
});