Is it possible to set a base URL for NodeJS app?

前端 未结 7 540
有刺的猬
有刺的猬 2020-11-29 19:51

I want to be able to host multiple NodeJS apps under the same domain, without using sub-domains (like google.com/reader instead of images.google.com). The problem is that I\

7条回答
  •  时光取名叫无心
    2020-11-29 20:18

    The express router can handle this since 4.0

    http://expressjs.com/en/api.html#router

    http://bulkan-evcimen.com/using_express_router_instead_of_express_namespace.html

    var express = require('express');
    var app = express();
    var router = express.Router();
    
    // simple logger for this router's requests
    // all requests to this router will first hit this middleware
    router.use(function(req, res, next) {
      console.log('%s %s %s', req.method, req.url, req.path);
      next();
    });
    
    // this will only be invoked if the path ends in /bar
    router.use('/bar', function(req, res, next) {
      // ... maybe some additional /bar logging ...
      next();
    });
    
    // always invoked
    router.use(function(req, res, next) {
      res.send('Hello World');
    });
    
    app.use('/foo', router);
    
    app.listen(3000);
    

    Previous answer (before express 4.0) :

    The express-namespace module (dead now) used to do the trick :

    https://github.com/visionmedia/express-namespace

    require('express-namespace');
    
    app.namespace('/myapp', function() {
            app.get('/', function (req, res) {
               // can be accessed from something.com/myapp
            });
    });
    

提交回复
热议问题