我正在尝试使用电子邮件和密码设置身份验证。以下是signup.ejs中的部分代码:
<% if (message.length > 0) { %>
<div class="alert alert-danger"><%= message %></div>
<% } %>
<!-- LOGIN FORM -->
<form action="/signup" method="post">
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password">
</div>
<button type="submit" class="btn btn-warning btn-lg">Signup</button>
</form>表单发布到/signup,这是我的快捷路线:
// process the signup form
app.post(
'/signup',
passport.authenticate('local-signup', {
successRedirect: '/profile', // redirect to the secure profile section
failureRedirect: '/signup', // redirect back to the signup page if there is an error
failureFlash: true // allow flash messages
})
)这是我使用的本地护照策略:
passport.use(
'local-signup',
new LocalStrategy(
{
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
// asynchronous
// User.findOne wont fire unless data is sent back
process.nextTick(function() {
// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ 'local.email': email }, function(err, user) {
// if there are any errors, return the error
if (err) return done(err)
// check to see if theres already a user with that email
if (user) {
return done(
null,
false,
req.flash('signupMessage', 'That email is already taken.')
)
} else {
// if there is no user with that email
// create the user
var newUser = new User()
// set the user's local credentials
newUser.local.email = email
newUser.local.password = newUser.generateHash(password)
// save the user
newUser.save(function(err) {
if (err) throw err
return done(null, newUser)
})
}
})
})
}
)
)这里有一个指向我的Github repo的链接,其中包含完整的代码。
我遇到的问题是,当我使用Postman在请求正文中使用电子邮件和密码进行post请求时,结果很好,并且我被成功重定向到配置文件路由。然而,当我试图通过在我的页面上填写表单来登录时,我被重定向回'/signup‘路由。有人能帮我解决这个问题吗?
发布于 2017-10-09 09:55:56
我找到了答案。原因是表单没有将电子邮件和密码值传递给req.body。我把app.use(bodyParser.json())改成了app.use(bodyParser.urlencoded({ extended: true })),它开始工作了。
https://stackoverflow.com/questions/46628069
复制相似问题