In Express, how does router.get('/') in my routes directory handle requests other than '/'?

242 views Asked by At

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.

3

There are 3 answers

0
Yves Kipondo On BEST ANSWER

You have register the usersRouter as a middleware which will be executed when the Request URI is prefixed with /users an example will be https://localhost:3000/users/ or http://localhost:3000/users/subroute

// attach `usersRouter` as middleware
app.use('/users', usersRouter);

If in your users.js you have define route like this

router.get('/', (req, res) => {});
router.post('/users', (req, res) => {});
router.get('/:userId', (req, res) => {});
router.delete('/:userId', (req, res) => {}); 

module.exports = router;

You'll have this list of routes

  1. GET => http://localhost:3000/users
  2. POST => http://localhost:3000/users/users/
  3. GET => http://localhost:3000/users/1
  4. DELETE => http://localhost:3000/users/1

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 the users.js file the application won't break as long you are trying to reach that router with http://...:../users/users.

Learn more about middleware Learn more about Express routing

2
jfriend00 On

When you do this:

app.use('/users', usersRouter);

That already filters to send ONLY requests that start with /users to the router. It also strips off the /users from the start of the path so the router itself will do matching on the reduced path that has /users stripped from it which for /users will just be /. For a URL like /users/something, the router will match against /something.

Thus router.get("/", ...) will match the original URL of /users, but not /users/something.

0
AudioBubble On

The line

app.use('/users', usersRouter);

will make the users router handle requests prefixed with /users. The router in the users file therefore handles not /, but /users because you told your app to use that particular router for /users/*. In reality, this is simply a shortcut of doing router.get('/users') instead.