Auto detect https in node server

This commit is contained in:
Fergal Moran
2016-02-03 21:13:23 +00:00
parent 9213574b91
commit f1df5f1fcd

View File

@@ -2,18 +2,24 @@
var errors = require('./components/errors');
var http = require('http');
var url = require('url');
function _parseUrl(u){
function _parseUrl(u) {
var parts = url.parse(u, true, true);
var path = parts.pathname.split('/').filter(function(arg){
var path = parts.pathname.split('/').filter(function (arg) {
return arg;
});
if (path.length == 2){
if (path.length == 2) {
//probably a mix, reconstruct url and return
return parts.protocol + "//" + parts.host + "/mix/" + path[1] + "/";
}
return u;
}
function isHttps(u){
var parts = url.parse(u, true, true);
return parts.protocol === 'https';
}
module.exports = function (app) {
app.route('/config')
@@ -35,13 +41,14 @@ module.exports = function (app) {
if (req.headers['user-agent'].indexOf('facebookexternalhit') > -1) {
var url = _parseUrl((app.get('apiUrl') + req.path + '/').replace(/([^:]\/)\/+/g, "$1"));
console.log('Api url: ' + url);
http.get(url, function (api_res) {
var fun = isHttps(url) ? https : http;
fun.get(url, function (api_res) {
var body = '';
api_res.on('data', function(chunk) {
api_res.on('data', function (chunk) {
body += chunk;
});
api_res.on('end', function() {
res.render('social/facebook/mix', JSON.parse(body));
api_res.on('end', function () {
res.render('social/facebook/mix', JSON.parse(body));
});
}).on('error', function (e) {
console.log("Got error: " + e.message);