Ashi Singh
Ashi Singh

Reputation: 1

Not Able to Login Without giving auth token in the header

Funtion that handles the Login Click (user puts email and password)

const handleSubmit = async (e) => {
  e.preventDefault();
  const response = await fetch('http://localhost:5000/api/auth/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ email: credentials.email, password: credentials.password })
  });

  const json = await response.json();

  if (json.success) {
    localStorage.setItem('token', JSON.stringify(json.authToken));
      showAlert('Successfully Logged in');
      navigate("/");    
  } else {
    alert("Invalid credentials");
  }
}

Backend Api Call (Using Nodejs and Express)

router.post("/login", fetchUser,
  [
    body("email", "Enter a valid email").isEmail(),
    body("password", "Password cannot be blank").exists(),
    ], async (req, res) => {
    let success = false;
    // if there are errors, handle them with bad requests
    const errors = validationResult(req);
    if (errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    try {
      const { email, password } = req.body;

      // Check if the user with requested email exists in the database
      let user = await User.findOne({ email });
      if (!user) {
        success = false;
        return res.status(400).json({ success, error: "Please enter the correct credentials" });
      }

      // Check if the user with requested passwork exists in the database
      const comparePassword = await bcrypt.compare(password, user.password);
      if (!comparePassword) {
        success = false;
        return res.status(400).json({ success, error: "Please enter the correct credentials" });
      }

      // Auth Token Generation using jwtToken
      const data = {
        user: {
          id: user.id,
        },
      };
      success = true;
      let authToken = jwt.sign(data, JWT_Secret);

      res.json({ success, authToken });

    } catch (error) {
      res.status(500).send("Internal error occured");
    }
  });

Req and Response

When I tried Hardcording the auth-token it worked

By clicking on login the new auth-token should be generated and set as 'token' in the local storage. Through which data will be accessed using different end points.

Upvotes: 0

Views: 163

Answers (1)

Murat Colyaran
Murat Colyaran

Reputation: 2189

At this line json.authToken is a string already. You don't need to stringify it again.

localStorage.setItem('token', JSON.stringify(json.authToken))

Just remove the function and it'll be fine.

localStorage.setItem('token', json.authToken)

Upvotes: 1

Related Questions