Skip to content

Instantly share code, notes, and snippets.

@e-mon
Last active August 29, 2015 14:00
Show Gist options
  • Save e-mon/11051260 to your computer and use it in GitHub Desktop.
Save e-mon/11051260 to your computer and use it in GitHub Desktop.
proxy servrer(response image converted base64 encoding)
app.get('/proxy', function(req,res){
var url, proxyReq, proxyRequest;
if (req.param('url')) {
url = require('url').parse(req.param('url'));
options = {
host: url.hostname,
port: '80',
path: url.pathname,
method: 'GET'
}
proxyReq = http.request(options,function(proxyResponse){
proxyResponse.setEncoding('binary');
var type = proxyResponse.headers['content-type'],
prefix = 'data:' + type + ';base64,',
body = '',
success = true;
proxyResponse.on('data', function(chunk) {
if (proxyResponse.statusCode === 200) {
body += chunk;
} else {
res.statusCode = proxyResponse.statusCode;
body += chunk;
success = false;
}
});
proxyResponse.on('end', function() {
if (success) {
var base64 = new Buffer(body, 'binary').toString('base64'),
data = prefix + base64,
obj = {
"src": url.href,
"data": data
};
res.contentType('application/json');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET,POST");
res.send(JSON.stringify(obj));
} else {
res.send(body);
}
});
});
proxyReq.on('error', function(err) {
console.log('error occ');
res.statusCode = 404;
res.send(err.message);
});
proxyReq.write('data\n');
proxyReq.write('data\n');
proxyReq.end();
}else{
res.statusCode=404;
res.send(err.message);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment