skip to Main Content

I am using fetch() to call a url as follow:

  const context = useContext(AuthContext);
  const navigate = useNavigate();

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    // console.log({
    // email: data.get("email"),
    // password: data.get("password"),
    // });
    if (data) {
      //TODO: Trigger a mutation or update
      fetch("http://localhost:4000/api/user/login", {
        method: "POST",
        crossDomain: true,
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json",
          "Access-Control-Allow-Origin": "http://localhost:4000",
        },
        body: JSON.stringify({
          email: data.get("email"),
          password: data.get("password"),
        }),
      })
        .then((res) => res.json())
        .then((result) => {
          console.log(result);
          if (result.token) {
            context.login(result);
            navigate("/Home");
          }
        })
        .catch((e) => console.log(e));
    } else {
      console.log("Login failed.");
    }
  };

{handleSubmit} is then triggered upon clicking on submit button on the page.

The login controller:

const login = async (req, res, next) => {
  function generateToken(user) {
    return jwt.sign(
      {
        id: user.id,
        email: user.email,
        username: user.username,
      },
      SECRET_KEY,
      { expiresIn: "1h" }
    );
  }

  const user = await User.findOne({ email });
  if (!user) {
    console.log("User not found.");
  }

  const match = bcrypt.compare(password, user.password);
  if (!match) {
    console.log("Wrong password.");
  }

  const token = generateToken(user);

  return { token };
};

Right now the error thrown is "User not found". I don’t understand why is there no user found as the user with the entered email address exists in my mongodb atlas.

Please provide some guidance. Cheers.

2

Answers


  1. You need to add the following code in your login controller .

    const {email} = req.body.email; 
    const user = await User.findOne({ email });
    

    And i can see from your comment that when you are submitting the form you are getting nothing back !
    I can see that you are returning the token . Instead you have to add the following code if everything goes well.

    res.json({token: token})
    

    Or

    res.status(200).json({token})
    

    If everything is fine then you will get a response like this:

    {
     token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
    }
    

    One more thing to handle

    if(!user) {
      //here you should use either of the following line 
      //next('No such user found')
      res.status(404).send('No user found with that email')
    }
     if (!match) {
        //here you should use either of the following line 
      //next('Password Mismatch')
      res.status(400).send('Password Mismatch')
      }
    

    Why is that ?
    Because if you don’t handle this type of errors your app will not respond!
    Cause it will stuck in the middleware lifecycle !

    Login or Signup to reply.
  2. const login = async (req, res, next) => {
      try {
        function generateToken(user) {
          return jwt.sign(
            {
              id: user.id,
              email: user.email,
              username: user.username,
            },
            SECRET_KEY,
            { expiresIn: "1h" }
          );
        }
        const { email } = req.body.email
        const user = await User.findOne({ email });
        if (!user) {
          console.log("User not found.");
          res.status(404).json({ error: "User not found!" })
        } else {
          const match = bcrypt.compare(password, user.password);
          if (!match) {
            console.log("Wrong password.");
            res.status(401).json({ error: "Wrong Password!" })
          }
          if (match) {
            const token = generateToken(user);
            res.status(200).json({ token });
          }
        }
      } catch (error) {
        return res.status(500).json({ error: error.message });
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search