2013-05-26 4 views
2

저는 base64 인코딩을 구현하려고 시도하는 node.js 초보자입니다. 내 서버가 base64 메시지를 수신/처리하지 않는 것 같습니다. 아래 코드 :node.js - http with 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 
});