How to mount express.js sub-apps?

匿名 (未验证) 提交于 2019-12-03 08:59:04

问题:

I have several apps that I'm trying to merge into a single "suite": 2 apps are standalone, one is simply an auth layer (using everyauth for FB Connect). I want to set it up like so:

  • / - (home) list of the apps
  • /auth - login for any app
  • /app1 - requires login via /auth to access
  • /app2 - (same)

I've considered leaving app1 and app2 standalone, with the top layer being a proxy, but I think it would be hard to share an auth system between them. Virtualhosts (via Connect) might work, but I don't necessarily want a DNS'd subdomain for each one. So instead I'd like to primary app to be the auth layer, and the others "mounted" into that one, with basepath set on each app to a sub-path. (basepath is mentioned in the express Guide but not documented well.)

They all use MongoDB, the auth layer uses connect-mongodb for sessions, so I'm hoping they'll be able to share the whole auth/session layer between them.

In another thread, "How to share sessions in mounted express apps", Stephen writes,

I have a fairly complex express based web application that is split up into a few sub apps which are also express apps (using app.use()) ...

So how does one use app.use() to mount a sub-app? I was simply trying to use var subApp = require('./subapp/app.js'), with listen() running only in the sub-app when ! module.parent (so not as a sub-app)... but that seems to load all the sub-app's paths straight into the parent app. I've tried setting basepath using app.set('basepath', '/subapp/'), app.basepath = '/subapp/', etc, both in the sub-app itself and from the parent app, but it doesn't seem to have any effect.

Mounting apps like this makes express incredibly flexible, but it's not clear how to do it... any advice would be extremely welcome!! (And I'm happy to share lessons from my everyauth implementation if anyone is struggling with that.)

回答1:

app.use(uri, instanceOfExpressServer)

Just make sure you don't call .listen on it.

The alternative is to use require("cluster") and invoke all your apps in a single master so that they share the same port. Then just get the routing to "just work"



回答2:

Not sure if this helps you but I was looking to prefix my API routes. What I did was that when I initialized the router, I added the mount path. So my configuration looks like this

//Default configuration app.configure(function(){     app.use(express.compress());     app.use(express.logger('dev'));     app.set('json spaces',0);     app.use(express.limit('2mb'));     app.use(express.bodyParser());     app.use('/api', app.router);     app.use(function(err, req, res, callback){         res.json(err.code, {});     }); }); 

Notice the '/api' when calling the router



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!