In app.js I have:
const routes = './routes/'
const usersRouter = require(routes +'users');
/*more code*/
app.use('/users', usersRouter);
In users.js, I have:
const express = require('express');
const router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
My question: How does router.get('/')
know to get the users file? Usually I would need to pass '/users'
to router.get(
. But with app.use('/users'
in app.js, all I need is router.get('/')
in users.js. In fact if I type router.get('/users'
in users.js the program breaks.
Learning Express, and I could use explanation of how this works.
You have register the
usersRouter
as a middleware which will be executed when the Request URI is prefixed with/users
an example will behttps://localhost:3000/users/
orhttp://localhost:3000/users/subroute
If in your
users.js
you have define route like thisYou'll have this list of routes
If the Request URI which you are trying to access is define in your express app, the handler will fallback to the Express buildin Error Handler.
So if you have define a router
router.get('/users', ...)
in theusers.js
file the application won't break as long you are trying to reach that router withhttp://...:../users/users
.Learn more about middleware Learn more about Express routing