Reputation: 19
Here is the URL in browser:
http://localhost:3001/user/59cc018171149931f4e435ac
This is the code for the route:
router.get("/new", middleware.userLoggedIn, function(req, res){
console.log(req.params.id);
//find user by id
User.findById(req.user._id, function(err, foundUser){
if(err) {
console.log(err);
} else {
res.render("characters/addCharacter", {user: foundUser});
}
});
});
This is the middleware:
middlewareObj.userLoggedIn = function(req, res, next) {
// eval(require('locus'));
if (req.isAuthenticated() && req.params.id.equals(req.user._id)) {
return next();
}
res.redirect("/login");
};`
When I run the app everything works fine. Expect the request on the route above, which giving me the error "TypeError: Cannot read property 'equals' of undefined". When I take off the middleware and try to console.log(req.params.id), it returns "undefined". What am I doing wrong?
Edit:
I have my route configured in app.js:
app.use("/user/:id/characters", characterRoutes);
So the ":id" is there.
When I use /new/:id
instead of /new
getting new error message:
"Cannot GET /user/59c23b864262fc2c186677be/characters/new"
Upvotes: 1
Views: 8045
Reputation: 49
This thread talks about needing to define the param in the .use(...)
For example:
app.use('/:param1', (err, req, res, next) => ...)
https://github.com/expressjs/express/issues/4298
Upvotes: 0
Reputation: 51
cast req.params into any first:
let params: any = req.params
and then params.id should work
Upvotes: 0
Reputation: 1354
You have to specify the parameter you want in your path, like so /new/:id
and then you can use req.params.id
in your code.
Here's the Express documentation for this part
Upvotes: 1
Reputation: 37343
use /new/:id
instead of /new
router.get("/new/:id", middleware.userLoggedIn, function(req, res){
console.log(req.params.id);
//find user by id
User.findById(req.user._id, function(err, foundUser){
if(err) {
console.log(err);
} else {
res.render("characters/addCharacter", {user: foundUser});
}
});
});
Upvotes: 2