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;
URL parameters are not exposed to routers. You have a couple of options here:
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.(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'));
/user/:id/profile
to /user
, then edit your router to listen on /:id/profile
(not recommended).