Home > Software design >  FETCH ERROR: POST http://localhost:3000/api/user/login 404 (Not Found)
FETCH ERROR: POST http://localhost:3000/api/user/login 404 (Not Found)

Time:02-15

Backend server is working perfectly fine, if post is conducted using postman, In order to avoid Cors policy error i tried saving proxy:localhost:5000 in package.json, but its not working and it is throwing a error. this "POST http://localhost:3000/api/user/login 404 (Not Found)" error is displayed on console

   import { useState } from "react";
    // import axios from "axios";
    import { Link } from "react-router-dom";
    import styles from "./styles.module.css";
    
    const Login = () => {
      //   const history = useHistory();
      const [data, setData] = useState({ email: "", password: "" });
      const [error, setError] = useState("");
    
      const handleChange = ({ currentTarget: input }) => {
        setData({ ...data, [input.name]: input.value });
      };
    
      const handleSubmit = async (e) => {
        e.preventDefault();
        const { email, password } = data;
        const res = await fetch("/api/user/login", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ email, password }),
        });
        const finalRes = await res.json();
        if (res.status === 422 || !data) {
          window.alert("Invalid Login");
        } else {
          window.alert("logged in");
          //   history.push("/");
        }
      };
    
      return (
        <div className={styles.login_container}>
          <div className={styles.login_form_container}>
            <div className={styles.left}>
              <form className={styles.form_container} onSubmit={handleSubmit}>
                <h1>Login to Your Account</h1>
                <input
                  type="email"
                  placeholder="Email"
                  name="email"
                  onChange={handleChange}
                  value={data.email}
                  required
                  className={styles.input}
                />
                <input
                  type="password"
                  placeholder="Password"
                  name="password"
                  onChange={handleChange}
                  value={data.password}
                  required
                  className={styles.input}
                />
                {error && <div className={styles.error_msg}>{error}</div>}
                <button type="submit" className={styles.green_btn}>
                  Sing In
                </button>
              </form>
            </div>
            <div className={styles.right}>
              <h1>New Here ?</h1>
              <Link to="/signup">
                <button type="button" className={styles.white_btn}>
                  Sing Up
                </button>
              </Link>
            </div>
          </div>
        </div>
      );
    };

    
    export default Login;

//backend code

const router = require("express").Router();
const User = require("../model/userSchema");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const {
  RegistrationValidation,
  LoginValidation,
} = require("../validation/validation");
router.post("/register", async (req, res) => {
  const { error } = RegistrationValidation(req.body);

  if (error) return res.status(400).send(error.details[0].message);

  //checking if email exists in the database

  const emailExists = await User.findOne({ email: req.body.email });

  if (emailExists) return res.send("email already exists");
  const pass = await req.body.password;
  const salt = await bcrypt.genSalt(9);
  const hashPassword = await bcrypt.hash(pass, salt);
  const user = new User({
    name: req.body.name,
    email: req.body.email,
    password: hashPassword,
  });
  const savedUser = await user.save();
  res.send(savedUser);
});

router.post("/login", async (req, res) => {
  const { error } = LoginValidation(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  //checking if email exists or not
  const user = await User.findOne({ email: req.body.email });
  if (!user) res.status(400).send("Invalid email/password");

  //Checking password is correct
  const validPass = await bcrypt.compare(req.body.password, user.password);
  if (!validPass) return res.status(400).send("Invalid email/password");

  //creating, assign token
  const token = jwt.sign({ _id: user._id }, process.env.JWTTOKEN);
  res.header("auth-token", token);
  res.send("gg logged in");
});
module.exports = router;

//index.js

const express = require("express");
const app = express();
const dotenv = require("dotenv");

dotenv.config();

//importing database conn
const conn = require("./db/conn");
conn();
//import routes

const authRoute = require("./routes/auth");

//middleware
app.use(express.json());

//route middleware
app.use("/api/user", authRoute);

const port = process.env.PORT;

app.listen(port, () => console.log(`gg server is runnig ${port}`));

CodePudding user response:

you can use this package to help : check it out there is a step by step explanation in there on how to use it.

  • Related