2

Basically what happened was we have an app server that is running express and routes to a bunch of SPAs. This was great but then we wanted to have an app that runs its own node/express script (ghost). I can't figure out how to set the route /ghost to go to ./webapps/ghost/index.js

Is this just not possible?

Z2VvZ3Vp
  • 7,033
  • 6
  • 21
  • 35
  • Do you want to have an Express application within another as a sub-route, or are you talking about proxying? – tadman Jul 08 '15 at 19:38
  • If index.js returns the express app, yes this is entirely possible. Just attach and route it like you would a router, and make sure index.js doesn't call .listen unless it isn't being included as a module. – Kevin B Jul 08 '15 at 19:40
  • @tadman I am not sure I understand the question. i would like to just do something like `app.get('/ghost','./webapps/ghost/index.js');` i started the index script with npm start and am doing the above code but it's not working. – Z2VvZ3Vp Jul 08 '15 at 19:43
  • What is `index.js`? If it's an Express router you *might* be able to do that, but you'd need to do it with `require`. If it's a whole other application, it's time to proxy it. – tadman Jul 08 '15 at 19:45
  • @tadman it is an application. It is this: https://github.com/TryGhost/Ghost/blob/master/index.js – Z2VvZ3Vp Jul 08 '15 at 19:46
  • This is the sort of thing you can do at the server level with the right virtual host configuration. Usually that's a lot easier than delegating through your Node app. Loading one application inside of another gets messy in a hurry. – tadman Jul 08 '15 at 19:47

1 Answers1

3

You need to redirect incoming requests to the ghost express instance. I have done so in my personal site by adding a /blog route to my primary express instance and forwarding any request to it to the ghost expresss instance. Check it out here: https://github.com/evanshortiss/evanshortiss.com/blob/master/server.js

The basic gist is that you do the following:

app.use('/blog', function(req, res, next) {
  // Forward this request on...
  return next();
}, ghostServer.rootApp); //...but we forward it to a different express instance

If you're running both as separate processes then you could use Apache or nginx to just redirect the requests. If you absolutely must use an express application to forward requests then try the node-http-proxy module.

If you need to proxy from express you could do this using the http-proxy module by Nodejitsu:

var proxy = require('http-proxy').createProxyServer({});

app.use('/blog', function (req, res) {
  // You may need to edit req.url (or similar) to strip the /blog part of the url or ghost might not recognise it
  proxy.web(req, res, {
    target: 'http://127.0.0.1:'+GHOST_PORT
  });
});
Evan Shortiss
  • 1,638
  • 1
  • 10
  • 15