从后端(nodejs)向前端(reactjs)发送错误消息时出现问题

时间:2020-08-20 19:43:17

标签: javascript node.js reactjs

我正在实现登录功能,因此,当用户输入错误的凭据时,我向前端传递了一个错误的“错误的凭据”,但是在前端,我收到了另一条错误消息。

这是相关的后端代码

exports.loginUser = async (req, res) => {
  try{
    const loggedinUser = await userService.loginUser(res, req.body);
    if(loggedinUser.error){
      throw new Error(loggedinUser.error); //loggedinUser.error is 'Wrong credentials'
    }
    const tokenPayload = {
      userName: loggedinUser[0].name,
      email: loggedinUser[0].email
    }
    const token = jwt.sign(tokenPayload, keys.JWT.TOKEN_SECRET, {expiresIn: '60m'} );
    const tokenData = {
      token: token,
      name: tokenPayload.userName,
      email: tokenPayload.email
    }
    const redirectURL = url.format({
      pathname: '/dashboard/buzz',
      query: tokenData
    });
    res.send({redirectTo: redirectURL});
  } catch(err){
    console.log(err); //prints wrong credentials
    res.status(400).json(err);
  }
} 

这是相关的前端代码

const loginHandler = ( event ) => {
        event.preventDefault();
        setShowValidationMessage(true);

        const loginDetails = {
            email: loginForm.email.value,
            password: loginForm.password.value
        }

        if(formIsValid){
            axios.post('http://localhost:5000/login', loginDetails)
                .then(res=>setRedirectURL(res.data.redirectTo))
                .catch(err=>{
                    console.log(err.message);// prints Request failed with status code 400
                });
        }
    } 

0 个答案:

没有答案