skip to Main Content

I’m encountering a 404 Not Found error when attempting to make a POST request to "/api/auth/signup" in my JavaScript application. I am trying to build a MERN application for a Modern Real Estate Marketplace.
Here is my code:
the sign up file:

   `import { useState } from "react";
     import { Link } from "react-router-dom";
     import loginImg from "../assets/login.png";
     export default function SignUp() {
       const [formData, setFormData] = useState({})
       const handleChange = (e) => {
       setFormData(
          {
            ...formData,
            [e.target.id]: e.target.value,
          }
        );
    
      };
      const handleSubmit = async (e) => {
        e.preventDefault();
        const res = await fetch("/api/auth/signup",
        {
          method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify(formData),
    }
    );
    console.log('Response:', res);
    const data = await res.json();
    console.log(data);

}
console.log(formData);
return (
<div>
<div><img><img</img>`</div>`
<div>

      <form onSubmit={handleSubmit}>
        <h1>SIGN UP</h1>
        <div>
        <input type='text' placeholder='username' id="username" onChange={handleChange}></input>
        </div>
        <div>
        <input type='email' placeholder='email' id="email" onChange={handleChange} ></input>
        </div>
        <div>
        <input type='password' placeholder='password' id="password" onChange={handleChange} ></input>
        </div>
        <div>
          <p><input type='checkbox'></input>Remember me</p>
        </div>
        <button>Sign Up</button>
        <p>Already have an account?</p>
        <button><Link to={"/sign-in"}>Sign In</Link></button>
      </form>
      </div>
    
    </div>

 )}

my vite.config file:

import react from '@vitejs/plugin-react-swc';
import { defineConfig } from 'vite';

// https://vitejs.dev/config/
export default defineConfig({
server: {
proxy: {
"/api": {
target: "http://localhost:3000",
secure: false,
},
},
},
plugins: [react()],
});

my index.js

import dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";
import authRouter from "./routes/auth.route.js";
import userRouter from "./routes/user.route.js";
dotenv.config();

mongoose.connect(process.env.MONGO).then( () => {
console.log("Connected to MongoDB!");
}).catch((err) => {
console.log(err);
});

const app = express();
app.use(express.json());

app.listen(3000, () => {
console.log("Server is running on port 3000");
}
);

app.use("/api/user", userRouter);
app.use("/api/auth", authRouter);

app.use((err, req, res, next) => {
const statusCode = err.statusCode || 500;
const message = err.message || "Internal Server Error";
return res.status(statusCode).json({
success: false,
statusCode,
message,
});
});

my auth controller file:

import bcryptjs from "bcryptjs";
import User from "../models/user.model.js";

export const signup=async (req,res, next) => {

const { username, email, password } = req.body;
const hashedPassword = bcryptjs.hashSync(password, 10);
const newUser = new User({ username, email, password: hashedPassword });
try {
await newUser.save();
res.status(201).json("User created successfully");
} catch (error) {
next(error);
}

};

my user model file:

import mongoose from "mongoose";

const userSchema = new mongoose.Schema( {
username: {
type: String,
required: true,
unique: true,

    },
    email: {
        type: String,
        required: true,
        unique: true,
    
    },
    password: {
        type: String,
        required: true,
        
    
    },

}, {timestamps: true});

const User = mongoose.model("User", userSchema);

export default User;

Any help in resolving this issue would be greatly appreciated. Thank you!

What I’ve Tried:

I’ve double-checked the URL to ensure it’s correct.
I’ve inspected the network request in the browser’s developer tools, and the request is being made as expected.
I manually added the "http://localhost:3000/api/auth/signup" instead of the /api/auth/signup"
and I still get the error. Any help in resolving this issue would be greatly appreciated. Thank you!

The error message in the console: POST http://localhost:5173/api/auth/signup 404 (Not Found)

3

Answers


  1. perform these 2 checks

    1. run only backed server, forget about frontend,just test your backend API with POSTMAN / CURL.
    2. Check your method type "GET/POST", in the Backend server.
    Login or Signup to reply.
  2. Well, I’ve never worked with vite, but what you can try is:

    • try to remove ‘proxy’ object from vite config and use this url in fetch ‘http://localhost:3000/api/auth/signup’ directly (instead of /api/auth/signup)

    If it will work after this change, then it means that the problem was in URL in fetch and vite proxy. We should check how it works exactly.

    Login or Signup to reply.
  3. Might because you’re using a relative path, and not the specific endpoint.

    Try using "http://localhost:3000/api/auth/signup&quot;.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search