我只是在服务器上编写一些端点时进行一些测试,我注意到一些非常奇怪的事情。这是我写的一些测试端点:
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
}
router.post("/test1", (req, res) => {
console.log("test1 endpoint reached");
res.send("test1 endpoint works");
});
router.post("/test2", ensureAuthenticated, (req, res) => {
console.log("test2 endpoint reached");
res.send("test2 endpoint works");
});
router.post("/test3/:tabId", (req, res) => {
console.log("test3 endpoint reached");
res.send("test3 endpoint works");
});
router.post("/test4/:tabId", ensureAuthenticated, (req, res) => {
console.log("test4 endpoint reached");
res.send("test4 endpoint works");
});
router.put("/test5/:tabId", (req, res) => {
console.log("test5 endpoint reached");
res.send("test5 endpoint works");
});
router.put("/test6/:tabId", ensureAuthenticated, (req, res) => {
console.log("test6 endpoint reached");
res.send("test6 endpoint works");
});
所有不使用ensureAuthenticated的测试都通过(1,3,5),而使用ensureAuthenticated的测试失败(2,4,6)。现在,我想也许 isAuthenticated() 不起作用,但我有一个实际的端点,它使用 EnsureAuthenticated 并且它工作得很好:
router.put("/updatePin/:tabId", ensureAuthenticated, (req, res) => {
const accountId = req.user.accountId;
const tabId = req.params.tabId;
const isPinned = req.body.isPinned;
User.findOneAndUpdate(
{ accountId: accountId, "tabs.tabId": tabId },
{ $set: { "tabs.$.isPinned": isPinned } },
{ new: true }
)
.then((updatedUser) => {
if (!updatedUser) {
throw new Error("User not found or tab not found");
}
res.json("Tab pin status updated!");
})
.catch((err) => res.status(400).json("Error: " + err));
});
任何人都可以解释为什么会出现这种情况吗?如果需要更多代码,请告诉我。
尝试
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
next('Not authenicated');
}
注意
next
块之后的 if
调用