I created the login module in react.js which used the Api that i created from my backend to login but it's can't work properly?

Viewed 18

This is my module which I used to login in my App but when I enter the correct credentials its return the authtoken which means its find the correct email ,password from database but its does not read the if statement and read the else one which is invalid credentials? I dont know why it's does not read the json.succcess

import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'

const Login = () => {
  let navigate = useNavigate();
  const [Credentials, setCredentials] = useState({ email: "", password: "" })
  const handleSubmit = async (e) => {

    e.preventDefault();
    const response = await fetch("http://localhost:5000/api/authent/login", {
      method: 'POST', // *GET, POST, PUT, DELETE, etc.

      headers: {
        'Content-Type': 'application/json',
        'auth-token': "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNjMxOWExYTFkODFhNGRjMDEwZjQ2YzAxIn0sImlhdCI6MTY2MzA3NTM5Nn0.YAuUGzZPUWCZfqyiMu_GoHQ8NLGu3bNZTfL8nTjL05k"

      },
      body: JSON.stringify({ email:Credentials.email, password:Credentials.password })




    });
    const json = await response.json()
    console.log(json);
    if (json.success) {
      //redirect
      console.log("success")
      localStorage.setItem('token', json.authtoken);
      navigate('/');
    }
    else {
      console.log("wrong credentials");
      alert("Invalid credentials")
    }
  }
  const onChange = (e) => {
    setCredentials({ ...Credentials, [e.target.name]: e.target.value })
  }
  return (
    <div className='container'>
      <form onSubmit={handleSubmit}>
        <div className="mb-3">
          <label htmlFor="email" className="form-label">Email address</label>
          <input type="email" className="form-control"  value={Credentials.email} id="email" name="email" onChange={onChange} aria-describedby="emailHelp" />
          <div id="emailHelp" className="form-text">We'll never share your email with anyone else.</div>
        </div>
        <div className="mb-3">
          <label htmlFor="password" className="form-label">Password</label>
          <input type="password" className="form-control"  value={Credentials.password} onChange={onChange} id="password" name="password" />
        </div>

        <button type="submit" className="btn btn-primary">Submit</button>
      </form>
    </div>
  )
}

export default Login
0 Answers
Related