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

前端 未结 7 539
有刺的猬
有刺的猬 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:11

    At the moment this is not supported, and it's not easy to add it on your own.

    The whole routing stuff is buried deep inside the server code, and as a bonus there's no exposure of the routes them selfs.

    I dug through the source and also checked out the latest version of Express and the Connect middleware, but there's still no support for such functionality, you should open a issue either on Connect or Express itself.

    Meanwhile...

    Patch the thing yourself, here's a quick and easy way with only one line of code changed.

    In ~/.local/lib/node/.npm/express/1.0.0/package/lib/express/servers.js, search for:

    // Generate the route
    this.routes[method](path, fn);
    

    This should be around line 357, replace that with:

    // Generate the route
    this.routes[method](((self.settings.base || '') + path), fn);
    

    Now just add the setting:

    app.set('base', '/myapp');
    

    This works fine with paths that are plain strings, for RegEx support you will have to hack around in the router middleware yourself, better file an issue in that case.

    As far as the static provider goes, just add in /mypapp when setting it up.

    Update

    Made it work with RegExp too:

    // replace
    this.routes[method](baseRoute(self.settings.base || '', path), fn);
    
    // helper
    function baseRoute(base, path) {
        if (path instanceof RegExp) {
            var exp = RegExp(path).toString().slice(1, -1);
            return new RegExp(exp[0] === '^' ? '^' + base + exp.substring(1) : base + exp);
    
        } else {
            return (base || '') + path;
        }
    }
    

    I only tested this with a handful of expressions, so this isn't 100% tested but in theory it should work.

    Update 2

    Filed an issue with the patch:
    https://github.com/visionmedia/express/issues/issue/478

提交回复
热议问题