1

I have a Node/Express app that looks like this:

app.use(foo)
...
app.get('/foo/bar', ...)
...
app.get('/index', ...)

And I want to extract the middleware and the routes so that now I can do:

app.use(myMiddlewareAndRoutes)
...
app.get('/index', ...)

So that myMiddlewareAndRoutes adds the middleware foo and the route '/foo/bar' that belongs to it.

How can I do this?

adelriosantiago
  • 7,762
  • 7
  • 38
  • 71
  • It does not make sense that middleware adds more routes. Middleware is called repeatedly on lots of incoming requests. You do not want it adding routes over and over and over again. What I would suggest is that you back up a couple steps and describe your actual problem rather than only describing your attempted solution to a problem you haven't fully described. – jfriend00 Oct 21 '20 at 03:20
  • Does this answer your question? [How to separate routes on Node.js and Express 4?](https://stackoverflow.com/questions/23923365/how-to-separate-routes-on-node-js-and-express-4) – Matt Oct 21 '20 at 03:22
  • Perhaps you want to use a separate router that has the `/foo` and `/foo/bar` routes on it and you can then `app.use(router)` in one statement. – jfriend00 Oct 21 '20 at 03:22

2 Answers2

2
var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
  res.send('About birds')
})

module.exports = router
var birds = require('./birds')

// ...

app.use('/birds', birds)
//or if you need it on root level
app.use('/', birds)
Robert
  • 2,538
  • 1
  • 9
  • 17
0

You want to create a separate Router object then add it as a middleware with the .use() function.

In the foo.js file I'm creating a new router and exporting it:

foo.js

const { Router } = require('express');
const router = Router();

router.get('/bar', (req, res, next) => {
    return res.send('bar');
});

module.exports = router;

Then importing it in the index.js file to add it as a middleware:

index.js

const express = require('express');
const foo = require('./foo.js');

const app = express();

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

app.get('/index', ...)

Now every route you define in foo.js will use the /foo prefix like /foo/bar.