【发布时间】:2022-01-15 14:24:54
【问题描述】:
如果在 MongoDB 上输入的用户名或密码不同,如何显示错误消息?我不知道我的方法是否正确,我一直无法解决这个问题。
如果 loginFailure() 调度函数启动,我如何向 UI 显示?如何将它呈现给 UI,告诉用户它是否有效。
类似的警告错误
用户名或密码错误
login.jsx
import React, { useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import { login } from '../../redux/apiCalls'
import './login.css'
const Login = () => {
const [username, setUsername ] = useState("")
const [password, setPassword ] = useState("")
const history = useHistory()
const dispatch = useDispatch()
const handleClick =(e) =>{
e.preventDefault()
if(login(dispatch,{username,password})){
setTimeout(function(){
window.location.reload();
},500);
console.log("Hello")
}
else{
console.log("Erorr")
}
}
return (
<div className="login">
<input type="text" placeholder="username" onChange={e=>setUsername(e.target.value)} />
<input type="password" placeholder="password" onChange={e=>setPassword(e.target.value)} />
<button onClick={handleClick}>submit</button>
</div>
)
}
export default Login
userRedux.js
export const userSlice = createSlice({
name: 'user',
initialState: {
currentUser: null,
isFetching: false,
error: false,
},
reducers: {
loginStart: (state) => {
state.isFetching = true
},
loginSuccess: (state, action) => {
state.isFetching = false
state.currentUser = action.payload
},
loginFailure: (state) => {
state.isFetching = false
state.error = true
},
logout: (state) => {
state.currentUser = false
},
},
})
export const { loginStart, loginSuccess, loginFailure, logout } =
userSlice.actions
export default userSlice.reducer
apicalls.js
export const login = async (dispatch, user) => {
dispatch(loginStart())
try {
const res = await publicRequest.post('/auth/login', user)
dispatch(loginSuccess(res.data))
} catch (error) {
dispatch(loginFailure())
window.alert('Wrong password or Username')
}
}
使用 windows.alert("wrong pass or username"),它可以工作,但是我可以为此渲染一个 Ui 吗?而不是弹出框?
loginAuth.js
router.post('/login', async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username })
!user && res.status(401).json('Wrong username')
const hashedPassword = CryptoJS.RC4.decrypt(
user.password,
process.env.SECRET_KEY
)
const OriginalPassword = hashedPassword.toString(CryptoJS.enc.Utf8)
OriginalPassword !== req.body.password &&
res.status(401).json('Wrong password')
const accessToken = jwt.sign(
{
id: user.id,
isAdmin: user.isAdmin,
},
process.env.JWT_SEC,
{ expiresIn: '3d' }
)
const { password, ...others } = user._doc
res.status(200).json({ ...others, accessToken })
} catch (error) {
res.status(500).json(error)
}
})
【问题讨论】:
标签: node.js reactjs authentication redux mern