我正在尝试构建一个登录身份验证,当用户输入正确时,它应该转到主页,如果没有,它应该将用户发送到登录页面。我通过检查200和400的状态来完成这项工作。当我输入错误的用户名时,服务器端确实返回400的代码。但是服务器端没有,即使用户不正确,它仍然会将我重定向到主页。为什么会这样呢?
import React, {useState} from 'react'
import './login.css'
import axios from 'axios'
import { useHistory } from "react-router-dom";
function Login() {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const [data, setData] = useState(null)
const history = useHistory()
const onChangeUsername = (e) => {
setUsername(e.target.value)
}
const onChangePassword = (e) => {
setPassword(e.target.value)
}
const onSubmit = (e) => {
e.preventDefault()
const users = {
username: username,
password: password
}
axios.post('http://localhost:4000/users/login', users)
.then(res => console.log(res.data))
}
const loginUser = () => {
axios.get("http://localhost:4000/users/login", {
withCredentials: true
}).then(res => {
if(res.status === 200) {
setData(res)
console.log(res.status)
history.push("/home")
}
else if(res.status === 400) {
history.push("/login")
}
console.log(res.status)
})
}
return (
<div>
<img src="https://www.freepnglogos.com/uploads/twitter-logo-png/twitter-logo-vector-png-clipart-1.png" className="twitterlogo____image"/>
<h1 className="login_____headertext">Log in to Twitter</h1>
<div className="placeholder_____global">
<form onSubmit={onSubmit}>
<input className="placeholder____div" placeholder="Phone, email or username" onChange={onChangeUsername}/>
<div>
<input className="placeholder____div" placeholder="Password" type="password" onChange={onChangePassword}/>
</div>
<div>
<button className="twitter___loginbuttonpage" onClick={loginUser}>Log in</button>
</div>
</form>
<div className="forgetPassword_____div">
<p>Forgot password?</p>
<p>·</p>
<p>Sign up for Twitter</p>
</div>
</div>
</div>
)
}
export default Login
服务器端:
const express = require('express');
const router = express.Router();
const Users = require('../models/users.model.js')
const passport = require("passport")
require('../authentication/passportConfig.js')(passport)
router.route('/').get((req, res) => {
Users.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error:' + err))
})
router.route('/login').post((req, res, next) => {
passport.authenticate("local" , (err, user, info) => {
if (err) throw err;
if (!user) res.status(400).send("No user exists");
else {
req.logIn(user, err => {
if (err) throw error;
res.status(200).send("Succesfully Authenticated")
})
}
})(req, res, next)
})
router.route('/login').get((req, res) => {
res.send(req.user)
})
router.route('/add').post(async(req,res) => {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
const username = req.body.username
const password = hashedPassword
const email = req.body.email
const phone = req.body.phone
const monthOfBirth = req.body.monthOfBirth
const dayOfBirth = req.body.dayOfBirth
const yearOfBirth = req.body.yearOfBirth
const newUsers = new Users({
username,
password,
email,
phone,
monthOfBirth,
dayOfBirth,
yearOfBirth
})
newUsers.save()
.then (() => res.json("User Added"))
.catch(err => res.status(400).json('error' + err))
})
module.exports = router
1条答案
按热度按时间vcirk6k61#
我想你把事情搞混了。。。您有两种不同的方法用于相同的目的。如果你使用
onSubmit
在表单中,则不需要使用onClick
在按钮上。你应该完全删除
loginUser
函数并将逻辑移动到onSubmit
方法如下也可以删除
onClick
处理程序,并将按钮类型设置为提交,如下所示