Created
August 18, 2014 06:51
-
-
Save fluxsaas/25247ab94d0668e4163e to your computer and use it in GitHub Desktop.
Node server for Backbone app with push state and redirects to Rails-API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Server to foreward ajax requests | |
// http://stackoverflow.com/questions/7559862/proxy-with-nodejs-and-express/20539239#20539239 | |
// http://stackoverflow.com/questions/10435407/proxy-with-express-js | |
var express = require('express'), | |
request = require('request'), | |
path = require('path'), | |
app = express(), | |
cson = require('cson'), | |
modRewrite = require('connect-modrewrite'), | |
configPath = "./app/config/environments/web.cson"; | |
var config = cson.parseFileSync(configPath); | |
var API_PROTOCOL = 'http'; | |
var API_SUBDOMAIN = 'demo'; | |
var API_DOMAIN = 'staffomatic-api.dev'; | |
var API_VERSION = 'V3'; | |
var apiUrl = function(req){ | |
var subdomain = req.headers.host.split('.')[0]; | |
var url = API_PROTOCOL + '://' + subdomain + "." + API_DOMAIN; | |
var withPath = url + req.originalUrl | |
return withPath; | |
} | |
// url's which should be redirected to the API | |
var redirectRegex = /\/api|\/system|api\/v3\/oauth/ | |
app.use(function(req, res, next){ | |
console.log('%s %s', req.method, req.url); | |
var match = req.originalUrl.match(redirectRegex); | |
if (!!match && match.length) { | |
var url = apiUrl(req); | |
req.pipe(request(url)).pipe(res); | |
}else{ | |
next(); | |
} | |
}); | |
app.use(modRewrite([ | |
'!\\.html|\\.jpg|\\.js|\\.css|\\.png|\\.svg|\\.eot|\\.ttf|\\.woff /index.html [L]' | |
])); | |
app.use(express.static(path.join(__dirname, 'public'))); | |
var server = app.listen(3000, function() { | |
console.log('server listening @ http://localhost:%d', server.address().port); | |
console.log('\nNode and POW setup:'); | |
console.log("make sure you use POW and add a port redirect \ | |
see http://differential.io/blog/serve-ruby-on-rails-php-and-node-with-pow-pow#node for an example configuration\ | |
should as simple as: cat ~/.pow/staffomatic-frontend => 3000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment