I’m building an express application that has a users table in its database and a friends table. The point of the friends table is to be a many-to-many table that keeps track of friend requests between users. Since friends are ultimately always going to be tied to users, I wanted my express routes for friends to be a child router to the users router. However, my req.params properties in the parent routes are not being passed down to my friends routes.
I’ve set up the users routes like this:
const friendRoutes = require("./friends");
const router = express.Router({ mergeParams: true });
router.use('/:username/friends', friendRoutes);
My only friends route for now is:
router.post("/request/:receiver", ensureCorrectUserOrAdmin, async function (req, res, next) {
try{
// validate that request follows friendNewSchema
const validator = jsonschema.validate(req.body, friendNewSchema);
if( !validator.valid ) {
const errs = validator.errors.map(e => e.stack);
throw new BadRequestError(errs);
}
// make new request with Friend.request
console.log("Friend Request Body: ", req.body);
console.log("Friend Request Params: ", req.params);
const friendRequest = await Friend.request(req.params.username, req.params.receiver);
console.log("Successfully made Friend Request: ", friend);
// return json of friendRequest with a status code of 201
return res.status(201).json({ friendRequest });
}
catch (err) {
return next(err);
}
});
The specific problem I am running into is that the route is /users/:username/friends/request/:receiver but the :username route variable is never defined when my friends route is called. I checked the middleware function and it never touches/modifies the req.params object. What should I do to get the child route to access the parent route variable?