我使用passport.js并编写了所有必要的代码,但我不明白如何将错误放在客户端?successRedirect
做得很好,但如果我输入了错误的密码,什么也不会发生,也不会显示任何消息。
护照配置. js
这是我初始化LocalStrategy
的函数
const LocalStratigy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
const initialize = (passport, getUserByEmail, getUserById) => {
const authenticateUser = async (email, password, done) => {
const user = getUserByEmail(email) //dont worry we cana emplimate this function latter
if (user == null) {
return done(null, false, {
messege: "No user with that email"
}) //done are a function used in the parameter
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, {
messege: "wrrong password "
})
}
} catch (error) {
return done(error)
}
}
passport.use(new LocalStratigy({
usernameField: 'email'
}, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize
服务器. js
此服务器端
app.post('/signin', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/signin',
failureFlash: true
}))
登录. html
在这个文件中,我在脚本中使用了js代码,但是它不起作用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="signup.css">
</head>
<body>
<div id="messeges">
</div>
<form action="signin" method="post">
<div class="box">
<div class="from">
<h2>Sign in</h2>
<div class="inputbox">
<input type="email" name="email" id="email" required="required">
<span>Email Adress</span>
<i></i>
</div>
<div class="inputbox">
<input type="password" id="password" name="password" required="required">
<span>Password</span>
<i></i>
</div>
<div class="links">
<a href="./signup.html">Forgot Password</a>
<a href="./signup.html">sign up</a>
</div>
<input type="submit" value="Login">
</div>
</div>
</form>
<script>
const messege = document.getElementById('messeges')
if (messages.error) {
messege.innerHTML = "<h1>messages.error</h1>"
}
</script>
</body>
</html>
1条答案
按热度按时间7ivaypg91#
我将如下修改app.post:
并且可能使消息div更健壮一些:
并删除html中的script标记。还要将其添加到serveur.js以解析服务器端代码中的请求主体。