Search code examples
javascriptexpressexpress-router

Request parameter in Express router


I'm having some trouble accessing request parameters in express router.

My server.js file has this:

app.use('/user/:id/profile', require('./routes/profile');

And this is in my ./routes/profile.js file:

router.get('/', (req, res) => {
    console.log(req.params.id);
}

But the console log prints undefined. I'm new to express and feel like I'm missing something basic about how routing works. Can someone please help me out?

Here is my full server.js:

const express = require('express');
const app = express();
app.use(express.json());

app.use('/user/:id/profile', require('./routes/profile'));

app.listen(5000, () => console.log('Listening'));

Here is my full profile.js:

const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
  console.log(req.params.id);
  res.status(200).send('In profile route');
});

module.exports = router;

Solution

  • URL parameters are not exposed to routers. You have a couple of options here:

    1. Parse req.originalUrl to get the user id (not recommended). req.originalUrl isn't affected by the router's mount point and will remain as /user/112/profile or whatever url you visited.
    2. Add some middleware to expose the id (recommended). Your new route statement will end up looking like this:

    (Now you can use req.userId in your profile.js)

    app.use('/user/:id/profile', function(req, res, next) {
        req.userId = req.params.id;
        next();
    }, require('./routes/profile'));
    
    1. Change the mount point from /user/:id/profile to /user, then edit your router to listen on /:id/profile (not recommended).