我正在尝试修复以下错误:
/home/ubuntu/workspace/src/util/utils.js:2
if (req.isAuthenticated()) {
^
TypeError: Cannot read property 'isAuthenticated' of undefined
at Object.isLogged (/home/ubuntu/workspace/src/util/utils.js:2:11)
at Object.<anonymous> (/home/ubuntu/workspace/src/routes/index.js:6:23)
我在我的应用程序中使用以下护照:
require('dotenv').config()
const express = require('express')
//...
const session = require('express-session')
const passport = require('passport')
// configure passport
require('./config/passport')(passport)
const auth = require('./routes/auth')
const index = require('./routes/index')
const app = express()
// ...
app.use(
session({
secret: 'super-mega-hyper-secret',
resave: false,
saveUninitialized: true,
})
)
app.use(passport.initialize())
app.use(passport.session())
app.use((req, res, next) => {
res.locals.currentUser = req.user
next()
})
// routes
app.use('/', auth)
app.use('/', index)
app.listen(port, host, () => {
console.log(`Listening on ${host}:${port}`)
})
module.exports = app
我的passport.js文件如下所示:
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const service = require('../service/auth')
module.exports = () => {
passport-serialize-deserialize
passport.serializeUser((user, done) => {
done(null, user.id)
})
passport.deserializeUser(async function(id, done) {
const user = await service.findById(id)
done(null, user)
})
passport.use('local', new LocalStrategy({
usernameField: 'username',
}, async(username, password, done) => {
const user = await service.signin(username, password)
done(null, user)
}))
}
当我的/
被调用时,我正在使用isLogged()
函数来控制是否需要登录:
const express = require('express')
const router = express.Router()
const utils = require('../util/utils')
router.get('/', utils.isLogged(), (req, res) => {
res.render('dashboard')
})
module.exports = router
函数的定义可以在我的utils.js
文件中找到,其中上面的错误日志指向:
function isLogged(req, res, next) {
if (req.isAuthenticated()) {
next()
} else {
res.redirect('/')
}
}
module.exports = {
isLogged,
}
完整的代码流可以在以下代表中找到:passport example
有什么建议我做错了吗?`
感谢您的回复!
答案 0 :(得分:1)
运行此代码时:
router.get('/', utils.isLogged(), (req, res) => {
res.render('dashboard')
});
正在执行的是utils.isLogged()
,此执行的结果被注册为中间件。
由于您尝试在没有传递任何参数的情况下执行它,res
将作为未定义传递,您将收到错误。
现在,你真正想做的是传递函数本身,而不是它的执行,所以当express将调用它(在请求处理期间)时,它会将参数传递给它。所以你的代码应该是这样的:
router.get('/', utils.isLogged, (req, res) => {
res.render('dashboard')
});