Home > database >  How do I output basic form validation errors that have been precoded into my backend, on my frontend
How do I output basic form validation errors that have been precoded into my backend, on my frontend

Time:07-03

I am currently working on a basic user registration project. I'm not sure on how to display messages such as "Invalid password", "You have successfully logged in", etc. that have been console.log in my backend, in my react front end.

Basically I just want any input from the client whether valid or invalid to output a message on my webpage after it passes through the backend code.

Here is my backend login code:

app.post("/login", (req, res)=> {
   console.log(req.body);
   const email = req.body.email;
   const password = req.body.password
   const sql_email = "SELECT * FROM userTable WHERE email = ?"; 
   connection.query(sql_email, [email], function (error, result) {
    if (!result.length) {
        console.log("User not found");
    } else {
        console.log(result[0].email);
        const verified = bcrypt.compareSync(password, result[0].password);
    if (verified){
        console.log("You have successfully logged in");
    } 
    else{
        console.log("Invalid password");
   }}});
}); 

And here is my front end login page

import React, {  useState } from "react";
import Axios from "axios";
import "../App.css";
import {Link} from "react-router-dom";
export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const infoentered = ()=>{
    console.log(email password);
    Axios.post('http://localhost:3000/login', {email:email, password: password}).then(()=>{
      console.log("success");
    })
  };
  return (
    <div className="App">
      <div className="details">
        <h2>Login</h2>
        <label>Email</label>
        <input type="text"onChange={(event)=>{
          setEmail(event.target.value);
        }}/>
        <label>Password</label>
        <input type="text"onChange={(event)=>{
          setPassword(event.target.value);
        }}/>
        <button onClick={infoentered}>Enter</button>
        <Link to="/forgotpassword" className="forgot-password">Forgot Password</Link>
      </div>
    </div>
  )
}

CodePudding user response:

Generally speaking, you should send a response to the client.

res.json({"some":"result"});

And on the client, receive it.

Axios.post('http://localhost:3000/login', {
  email: email,
  password: password
}).then(response => {
  const obj = response.data
  console.log("success", obj);  
})

CodePudding user response:

So all you need here is a conditional rendering in your Login, but first you need to send a response from your express server to your react when credentials are true or false like this :

Server.js

app.post("/login", (req, res)=> {
   console.log(req.body);
   const email = req.body.email;
   const password = req.body.password
   const sql_email = "SELECT * FROM userTable WHERE email = ?"; 
   connection.query(sql_email, [email], function (error, result) {
    if (!result.length) {
        console.log("User not found");  
        //here basically I'am sending a code red 404 
         return res.sendStatus(404);
    } else {
        console.log(result[0].email);
        const verified = bcrypt.compareSync(password, result[0].password);
    if (verified){
        console.log("You have successfully logged in");  
        //And here I'm sending a 200 code(OK), check http status code
        return res.sendStatus(200);
    } 
    else{
        console.log("Invalid password");  
        //Also here I'am sending an error code 404
        return res.sendStatus(404);
   }}});
}); 

Login

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");  
  const [showError, setError]= useState(false);

  const infoentered = ()=>{
    console.log(email password);  
    //Here in the .then it means your axios operation received an ok code 200 and you can redirect your user to his account or whatever  
// but in the catch it received an error so we check if it's an 404 error to set our showError state to true to show the errors
    Axios.post('http://localhost:3000/login', {email:email, password: password}).then(()=>{
      console.log("success");
    }).catch((err)=>{  
        if(err.response.status===404) {  
          setError(true); // this is the condition that's gonna help render the error conditionally 
}
})
  };
  return (
    <div className="App">
      <div className="details">
        <h2>Login</h2>
        <label>Email</label>
        <input type="text"onChange={(event)=>{
          setEmail(event.target.value);
        }}/>
        <label>Password</label>
        <input type="text"onChange={(event)=>{
          setPassword(event.target.value);
        }}/>  
//and here is the conditional rendering so it only shows the errors when the showError state is true
{showError && <p style={{color:'red'}}>Invalid username or/and password, please try again!</p>}
        <button onClick={infoentered}>Enter</button>
        <Link to="/forgotpassword" className="forgot-password">Forgot Password</Link>
      </div>
    </div>
  )
}
  • Related