【发布时间】:2021-03-06 22:26:34
【问题描述】:
我正在学习使用 Express.js 创建 Web 应用程序。 在此过程中,我们尝试实现一项功能,以防止用户在未登录时访问某些页面。
// teamController.redirectView : Redirect the screen according to res.locals.redirect
app.get('/user/:id/team/member', teamController.showMember, teamController.redirectView)
// The following is a middleware function written in another file(teamController.js)
showMember: (req, res, next) => {
// I want to set the redirect to the '/login' and skip the following process when no user are logging in.
if(!res.locals.loggedIn) {
res.locals.redirect = 'login'
next()
}
// access the property that is set only when the user logs in
let userID = res.locals.currentUser.userID
// Other processes...
当我在用户未登录的情况下访问URI时,我确实被带到了登录页面,但是我在控制台中得到了以下错误。
TypeError: Cannot read property 'userID' of undefined
at // the position of 'let userID...'
Error occured: TypeError: Cannot read property 'userID' of undefined
// Abbreviated below...
这是否意味着执行 next() 不会像 'return' 那样跳过后面的过程? 或者是否存在导致此错误的致命错误? 你能帮帮我吗?
我本可以通过将所有后续进程包含在“else”中来避免该错误,但如果有更好的方法,如果您也能告诉我,我将不胜感激。
【问题讨论】: