reactjs - axios bad request debug 404 - Stack Overflow

admin2025-05-02  1

I am working on setting up a login system with both a frontend and a backend. I'm encountering an error and want to understand it more clearly. What steps can I take to debug this? My folder structure is as follows.

backend
|
|---index.mjs
|
| ---routes
|         |-auth.mjs // login/register
|
|---stat
       |-local-strat.mjs  //for my passport local srat

this is the auth.mjs

import express from "express";
import bcrypt from "bcrypt";
import db from "../data.mjs";
import passport from "passport";
import flash from "connect-flash";

//Express
const app = express();

// Flash
app.use(flash());

// Register
app.post("/register", (req, res) => {
  const { fname, lname, email, password } = req.body;

  const query =
    "INSERT INTO userlogin (`fname` , `lname` , `email` , `password`) VALUES (?, ?, ?, ?)";
  const query2 = "SELECT * FROM userlogin WHERE email = ?";

  try {
    db.query(query2, [email], async (err, result) => {
      if (err) {
        console.log("Error Email is already registered");
        req.flash("reg_fail", "You Failed to Register");
        return res.status(500).json({
          message: "Server error during email check",
          flash: req.flash("reg_fail"),
        });
      }
      if (result.length > 0) {
        req.flash("reg_success", "You Registed Nice!");
        return res.status(400).json({
          message: "Email already exist, try to Login",
          flash: req.flash("reg_success"),
        });
      }

      const hash = await bcrypt.hash(password, 10);

      if (result.length === 0) {
        db.query(query, [fname, lname, email, hash], (err, result) => {
          if (err) {
            return res.status(400).send({ message: "Error with password" });
          }
          console.log(result);
          req.flash("reg_success", "Your Now registered and Can now login in!");
          return res.status(200).send({ message: "Account was made!" });
        });
      } else {
        console.log("error making an account!");
      }
    });
  } catch (error) {
    return res.status(500).send({ message: "Server Error" });
  }
});

// Login
app.post(
  "/login",
  passport.authenticate("local", {
    successRedirect: "/login/success",
    successFlash: true,
    failureRedirect: "/login",
    failureFlash: true,
  }),
);

app.get("/login/success", (req, res) => {
  return res.json({ name: req.user.fname });
});

export default app;

I keep getting a 404 error stating that it can't find the /login route, even though the route exists and the port number matches the server-side configuration. What could be causing this, and how can I debug it?

This is the frontend

const onSubmit: SubmitHandler<formInput> = async (data) => {
    try {
      const response = await axios.post(
        "http://localhost:3001/login",
        {
          email: data.email,
          password: data.pass,
        },
        {
          withCredentials: true,
          timeout: 5000,
        },
      );

      if (response.status == 200) {
        router.push("/login/success");
        // console.log("Login successful:", response);
      } else if (response.status === 400) {
        console.log("Bad request:", response.data.message);
      } else {
        console.log(`Unexpected status code: ${response.status}`);
      }
    } catch (error: any) {
      console.error(
        "Error occurred during Login:",
        error,
        seterrorMessage(error.message),
      );

      if (error.response) {
        seterrorEmail(error.response.data.message);
        console.error("Response error details: ", error.response);
      } else if (error.request) {
        console.error("No response received from the server: ", error.request);
      } else {
        console.error("Unexpected error:", error.message);
      }
    }
  };
转载请注明原文地址:http://anycun.com/QandA/1746139440a92122.html