User is not Verifying, while login in Reactjs
Problem Description:
Hello I am new to reacts. I am implementing reactJs Login system. I want to verify my user from backend(MongoDb) then to show User Dashboard. I tried some similar problems but didn’t get my solution
What is Problem
Whenever i am trying to login, by giving username and password, it redirects to user dashboard. By giving wrong email or password also it goes to user dashboard
what i Tried
I tried all the logic behind but the problem is same
Login.jsx(react)
import React, { useState } from 'react'
import { NavLink } from 'react-router-dom'
import zerotwo from "../images/02.svg"
import { useNavigate } from 'react-router-dom';
const Login = () => {
const navigate = useNavigate()
const [detail, setDetail] = useState({
email: "",
password: "",
})
let name, value
const handleInput = (e) => {
name = e.target.name
value = e.target.value
setDetail({ ...detail, [name]: value })
}
const PostData = async (e) => {
e.preventDefault()
const { email, password } = detail
const res = await fetch("/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
email, password
})
})
const data = await res.json()
if (data === 400 || !data) {
alert("not registered")
navigate('/')
} else {
alert("Sucesssfuly")
navigate('/dashboard')
}
}
app.js(backend)
router.post("/login", async (req, res) => {
let token
try {
const { email, password } = req.body
if (!email || !password) {
return res.status(400).json({ message: "fill the credentials" })
}
const UserLogin = await User.findOne({ email: email })
if (UserLogin) {
const passmatch = await bcrypt.compare(password, UserLogin.password)
token = await UserLogin.generateAuthToken()
// console.log(token);
res.cookie("jwt",token,{
expires : new Date(Date.now()+25892000000),
httpOnly : true
})
if (!passmatch) {
res.status(400).json({ error: "Invalid credentials" })
}
else {
res.status(200).json({ message: "sign in successfully" })
}
} else {
res.status(400).json({ error: "Invalid credentials" })
}
} catch (err) {
console.log(err);
}
})
I tried all logics behind in verifying username and password.
I am expecting to verify user properly by his/her username and password
Solution – 1
You are checking data
object on status code here – data === 400
, but it will never be true, cause you returning object { error: "Invalid credentials" }
if creds are invalid.
You probably wanted to check the response status code, so it should be
if (res.status === 400)
Also, side note – I would recommend to return 401
status code for Authentication error (wrong password), it specifically designed for such cases and it is standard. 400
in this case could be if for example empty username
or password
were provided – that would make sense, cause 400
error is more for validation.