我有一条类似这样的路线:
router.get("/users/:id/thing", middlewareObj.isLoggedIn, function(req, res){
res.render("thing.ejs");
});
我希望只有当前用户的 ID 与路由中的“:id”匹配时才能访问此路由。我该怎么做呢?非常感激。
最佳答案
您可以将登录的用户(我假设您在 req.user 中有它[实际上您应该检查护照])与参数 ID 进行比较:
if(req.user.id != req.params.id) return res.status(400);
您可以从 URL 中删除 id 并简单地使用记录的用户数据。因为如果 url id 与用户 id 相匹配,你就有了多余的东西。所以,有了这个..
router.get("/users/thing", middlewareObj.isLoggedIn, function(req, res){
let id = req.user.id;
//do something with the ID which you assume you do, otherwise why you want the ID in the first place
...
//return the view
res.render("thing.ejs");
});
关于javascript - 如果当前用户的 ID 与所述路由中的 ID 匹配,如何只允许访问该路由? Node JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46475215/