我在登录时验证凭据时尝试为用户设置会话时收到一个未定义的错误。我正在尝试使用express会话为用户创建会话,但没有将其直接导入到文件中(指导我不要这样做(,但不确定如何解决给定的错误。任何帮助和见解都将不胜感激!
终点:
router.post("/login", async (req, res, next) => {
try {
const { username, password } = req.body
// * checks for record existence in db, assigns record to var for access
const user = await users_access.findByFilter({ username })
if (!user) {
return res.status(401).json({ message: 'invalid crededentials' });
}
// * compares the entered password to the hash on record
const passwordValid = await secure.compare(password, user.password)
// * handling invalid responses + creating session
if (!passwordValid) {
return res.status(401).json({ message: 'invalid credentials' });
}
req.session.user = user
res.json({ message: `welcome, ${user.username}!`})
} catch(error) {
next(error)
}
});
应用模型:
// * add users to the datbase
// * inserts argument into user table in db access
// * returns a user found by id
const add = async (user) => {
const [id] = await database_access("users")
.insert(user)
return findById(id)
}
// * find user record with username and password
const find = () => {
return database_access("users").select("id", "username")
}
// * find user by filter
const findByFilter = (filter) => {
return database_access("users")
.select("id", "username", "password")
.where(filter)
.first()
}
// * find user with id
const findById = (id) => {
return database_access("users")
.select("id", "username")
.where({ id }) // desctructuring id from the request
.first()
}
module.exports = {
add,
find,
findByFilter,
findById
}
如果你需要看到任何额外的代码来评估,我很乐意提供,但相信这是每个错误响应的问题来源。提前感谢!
所以我猜您在服务器的入口文件中使用express-session
模块,app.js
、server.js
、index.js
,不管您怎么称呼它。
此登录处理程序需要在会话可用的上下文中使用。
我认为你想要的不是这个特定路由器的单元测试,而是集成测试,在你的应用程序中测试这个路由器。
这就是我从你提供的信息中所能看到的全部内容。如果这还不够有用,也许你可以向我们展示你的服务器主文件。以及这个路由器是如何使用的。