0
votes

When login gets failed in server side res.status(403).json({ fail: "Login failed" }); message from server side is passing into front end setHelperText(failMessage); How can i get the 'Login Failed' message in front end ?

It is displaying error in chrome console >> Error: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17)

server.js

app.post('/service/login', async (req, res) => {
  try {
    const userEmail = req.body.email;
    const userPassword = req.body.password;
    const loginData = await UserModel.findAll({ where: { email: userEmail} });
    const password = loginData[0].password;
    const email = loginData[0].email;
    if(password === userPassword && email === userEmail){
     const privilege  = loginData[0].privilege;
      res.status(200).json({ success: true, privilege, email });
    }else{
      res.status(403).json({ fail: "Login failed" });
    }
  } catch (e) {
    res.status(500).json({ message: e.message });
  }
});

Login.js

const fetchData = async () => {
  try {
    const res = await axios.post('http://localhost:8000/service/login', { email , password });
    console.log("Front End success message:"+res.data.success);
    if(res.data.success){
      setHelperText("Login successfully");
      setValue(res.data.privilege);
      setError(true);
    }
    else{
      const failMessage = res.data.fail;
      setHelperText(failMessage);
    }
  } catch (e) {
    console.log(e);
  }
}
1

1 Answers

1
votes

If the response is not success, (403 in your case), catch block will be executed, so move your logic inside the else block to catch block in the Login.js

catch(e) {      
const failMessage = e.response.data.fail;
setHelperText(failMessage);
// console.log(e.data.response); -> to print the server response
}