Whenever I try to send a POST request to "/api/auth/signup"
in my JavaScript application, I keep getting a 404 Not Found error. My goal is to create a MERN application for a Modern Real Estate Marketplace.
This is the code snippet causing the issue:
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>
)
}
vite.config
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()\],
});
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,
});
});
Auth controller
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);
}
};
User model
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;
My Attempts to Resolve the Issue:
I made sure that the URL is correct. I checked the network request using the browser's developer tools and confirmed that it's being sent correctly. Even when manually entering "http://localhost:3000/api/auth/signup" instead of just /api/auth/signup", the error persists. Any guidance on how to fix this problem would be highly appreciated. Thank you!
The console displays this error message: POST http://localhost:5173/api/auth/signup 404 (Not Found)