Home > Blockchain >  make login page with post request
make login page with post request

Time:12-25

I want to make a login page. But the problem is that even though the data I entered is wrong, it redirects to the page. how can i fix this?

I only have email and password information in my table

const client = require('../../db')
const express = require('express');
const app = express();
const cors = require("cors");

app.use(cors());
app.use(express.json()); //req.body

app.listen(2121, ()=>{
    console.log("Sever is now listening at port 5000");
})

client.connect();



app.post("/login", async (req, res) => {
  try {
    const { email, password } = req.body;

    const user = await client.query(
      `SELECT * FROM users WHERE email=$1 AND password=$2`,
      [email, password]
    );
    
    if (user.rows.length === 0) {
      res.send("Kullanıcı adı veya şifre yanlış");
    } else {
     res.send("Kullanıcı adı veya şifre doğru");// Eşleşen kullanıcı bilgileri varsa diğer sayfaya yönlendir
    }
    
  } catch (err) {
    console.error(err.message);
  }
});

this is my database code.when i run my database query in postman it works correctly

import React, { useState } from 'react'
import Navbar from '../../common/Navbar/Navbar';

const User = () => {
 
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
  const [user, setUser] = useState([]);
  const [error, setError] = useState('');

  const onSubmitForm = async e => {
    e.preventDefault();
    try {
      const response = await fetch(`http://localhost:2120/login`,{
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      

      if (response.ok) {
       
        window.location.replace(`/AdminPage.js`);
      } else {
        setError('Invalid email or password');
      }
    } catch (err) {
        console.error(error);
        setError('An error occurred. Please try again later.');
    }
  };


  return (
    <>
    <Navbar/>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3 Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"></link>
    <div className="container text-center">
        <h1 className="my-5">Search for the Dormitory You Want</h1>
        <form className="d-flex" onSubmit={onSubmitForm}>
          <input
            type="text"
            name="name"
            placeholder="Enter email ..."
            className="form-control"
            value={email}
            onChange={e => setEmail(e.target.value)}
          />
          <input
            type="text"
            name="name"
            placeholder="Enter password ..."
            className="form-control"
            value={password}
            onChange={e => setPassword(e.target.value)}
          />
          
          <button className="btn btn-success">Submit</button>
        </form>
        
        
      </div>
    </>
  )
}

export default User

this is my login page code.

CodePudding user response:

The issue is related backend side since when you are sending the wrong login and password, you are still responding as a 200 ok. By default the HTTP status code sent in a response from an Express application is 200 (OK). Instead of that, you can just throw an error message with 404 status. In addition, if there is another issue that is not related correction of credentials you may to response 500 status code as an internal error. I have added inside catch.

app.post("/login", async (req, res) => {
  try {
    const { email, password } = req.body;

    const user = await client.query(
      `SELECT * FROM users WHERE email=$1 AND password=$2`,
      [email, password]
    );
    
    if (user.rows.length === 0) {
      res.status(404).send("Kullanıcı adı veya şifre yanlış");
    } else {
     res.send("Kullanıcı adı veya şifre doğru");// Eşleşen kullanıcı bilgileri varsa diğer sayfaya yönlendir
    }
    
  } catch (err) {
     response
    .status(500)
    .json({ message: "Error in invocation of API: /login" })
  }
});
  • Related