【发布时间】:2020-01-29 09:51:26
【问题描述】:
我正在使用 Node、MongDB、Passport、Express 和 React 开发一个身份验证应用程序。我试图解决这个问题 2 天,但仍然卡住了。错误是在数据发送到服务器后,服务器不处理该请求。这是我的配置:
护照本地配置
const LocalStrategy = require('passport-local').Strategy
passport.use({
usernameField: 'username',
passwordField: 'password'
}, new LocalStrategy((username, password, done) => {
/*Match username or not*/
User.findOne({ email: username }, (err, user) => {
if (err) {
console.log(`Error: ${err}`)
return done(err)
}
/* user not found */
if (!user) {
console.log(`User not matched!`)
return done(null, false, {
message: 'That email is not registered'
})
}
/*Match password*/
bcrypt.compare(password, user.password, (err, isMatch) => {
if (err) throw err
if (isMatch) {
return done(null, user)
} else {
return done(null, false, {
message: 'Password incorrect'
})
}
})
})
}))
身份验证路由器
router.post('/auth/local/login', (req, res, next) => {
console.log(`Login info: ${JSON.stringify(req.body)}`)
passport.authenticate('local', {
successRedirect: "/dashboard",
failureRedirect: "/login",
failureFlash: false
})
})
客户端
formData.append('username', username)
formData.append('password', password)
const data = new URLSearchParams(formData)
fetch('/auth/local/login', {
method: 'POST',
body: data
})
.then(res => res.json())
.then(json => {
console.log(`${JSON.stringify(json)}`)
handleAuthenticated(json)
})
.catch(err => console.log(err))
在服务器端登录
Server started successfully at 3001!
Database connected successfully!
Login info: {"username":"newemail@yahoo.com","password":"123456"}
浏览器检查
【问题讨论】:
-
任何控制台错误?对于 FE 和 BE。也许是一些 CORS 标头问题?
-
未发现错误。在我的情况下,来自客户端的请求已成功发送到服务器,但服务器没有处理任何内容。所以我认为问题不来自CORS。用户提交登录按钮后,状态为pending,1、2分钟后变为failed。
标签: reactjs mongodb express authentication passport-local