简体   繁体   中英

Express.js - prepend sub-route to all defined routes

Let's say I have an Express app defined in a file, say server.js like this:

const app = express();

app.use('/foo', foo);
app.use('/bar', bar);

module.exports = app;

I import this Express app in another file, say index.js :

const app = require('./server');

const port = process.env.PORT || 3000;

const listen = (port) => {
    app.listen(port, () => {
        console.log(`Backend listening on port ${port}!`);
    });
};

listen(port);

Now, the routes that are available for this app are /foo and /bar .

Is there a way to edit configuration in the index.js file so that the routes become /api/foo and /api/bar ? Without touching server.js file.

Use case:

I have a Nuxt.js app with a backend that is loaded into the Nuxt app via serverMiddleware property in nuxt.config.js like this:

serverMiddleware: [
    ...
    { path: '/api', handler: '~/server.js' },
],

This has the effect similar to what I described above: it imports the express app from server.js app and prepends all its routes with /api .

However, often I don't want to develop the frontend part of the Nuxt app, I just want to do changes on the backend. For this purpose I have a helper file like index.js above, which runs backend only. (Frontend often takes long time to compile, that's why I don't want to compile it when I don't need to.)

This creates a problem that all the routes are slightly different - they lack the /api at the beginning. The routes are being used in different tools like Postman etc. and suddenly they wouldn't work.

My current solution is to define index.js file in the same way as server.js file with all routes defined like I want them - instead of app.use('/foo', foo); there's app.use('/api/foo', foo); etc. but this has its own problems, eg if I change server.js I have to change index.js . I am looking for something more elegant.

According to the express 4.0 docs https://expressjs.com/en/4x/api.html#app.use you can use an application instance the same as you would a router . In short, just use the export of your server.js as a middleware at the route in which you want to insert it, as opposed to directly calling .listen() on it.

Here is some demo code that worked for me:

const express = require('express');
const app_inner = express();
app_inner.use('/foo', (req,res) => res.send('foo'));

const app_outer = express();
app_outer.use('/foo2', app_inner);

app_outer.listen(9999);
// web browser at localhost:9999/foo2/foo returns 'foo' as expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM