【问题标题】:How can I show error message when wrong password or username?密码或用户名错误时如何显示错误消息?
【发布时间】: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


    【解决方案1】:

    一个简单的解决方案是设置一个状态,例如;

    const [loginErr, setLoginErr] = useState(false);

    然后,当您的登录函数返回 false 时,您可以这样做;

        const handleClick =(e) =>{
            e.preventDefault()
               if(login(dispatch,{username,password})){
                 setTimeout(function(){
                     window.location.reload();
                     },500);
                    console.log("Hello")
         
               }
               else{
                   setLoginErr(true);
               }
        }
    

    然后,进行条件渲染;这可能是一个组件,也可能只是一个 div,表示您要显示的错误;

    <>
      { loginErr ? <SomeError /> : null }
    </>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-13
      • 2014-09-24
      • 2013-05-25
      • 1970-01-01
      • 2012-08-26
      • 2018-11-20
      • 1970-01-01
      • 2022-10-14
      相关资源
      最近更新 更多