The POST request to the localhost API endpoint resulted in a 404 Not Found error

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)

Answer №1

complete these two verifications

  1. execute the backend server only, disregard the frontend, and evaluate your backend API using POSTMAN / CURL.
  2. Validate the method type as "GET/POST" on the Backend server.

Answer №2

While I don't have prior experience with vite, here's a suggestion to consider:

  • Attempt removing the 'proxy' object from the vite configuration and utilize the fetch URL 'http://localhost:3000/api/auth/signup' directly instead of '/api/auth/signup'

If this adjustment proves successful, it indicates that the issue potentially lies in the URL within the fetch method and the vite proxy setup. Further examination is recommended to fully understand its functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The integration of Angular and Node API within the IISNode directory structure is experiencing functionality issues

Read more about the question I have successfully set up my Node API and Angular component with IISnode. However, when accessing the application from the IIS server, I noticed that they are showing in different directories (see image below). Additionally, I ...

The second function is not being executed during the callback

I've done some research on callbacks, but I'm still having trouble with my code. I've defined my functions and tried to run them onload, but something isn't quite right. The getelements() function works fine on its own. My goal is to l ...

Utilize a single WebAssembly instance within two separate Web Workers

After compiling a wasm file from golang (version 1.3.5), I noticed that certain functions using goroutines are not supported. When these functions are called, they run in the current thread and slow down my worker significantly. To address this issue, I w ...

Is there a way to automatically redirect my login page back to the original page in case of login failure?

I'm currently working on a basic login page using express.js + E.js. If the login credentials are incorrect, I have a variable badLogin that is triggered (see below). However, my goal is to redirect the website back to the login page instead of remai ...

RetrieveByUserIdentifier as a callback method (express)

Can you help me refactor the code below to use a callback function instead? I want to ensure that the Req and Res logic is handled separately. Userservice.js function getByUserId(req, res, next) { let userIDD = req.body.userID; User.findOne({ use ...

Using template expressions to access properties that contain spaces

Here is the code structure that I am working with: "name": { "age": [ { "data": { "how old": "23" } }, One of my JSON keys has a space in it. How can I access this pr ...

How to Upload Your Avatar Image with the Stream-Chat API from GetStream.io

I am currently in the process of developing a Stream-Chat API project and I want to allow users to upload images directly from their devices. Upon testing, everything seems to be working fine, but the uploaded image is not displayed - only the default avat ...

Implementing AJAX to dynamically update information based on user's selection from a dropdown

I need to dynamically adjust the opacity of my graph bars without requiring the user to manually refresh the page. I'm considering using AJAX for this purpose. How can I implement this functionality? const opacitySlider = document.getEle ...

Tips for boosting the efficiency of replaceWith on Internet Explorer 11

When rendering an array of data in a table element, there is a need for the table to be updated with new data as it can be filtered dynamically. However, I have encountered a performance issue specifically on IE11 when trying to render 1700 data entries us ...

AngularJS- numerous unique directives featured on a single page each with its distinctive state

Regarding the query about Calling a method in a directive controller from another controller. Is there a way to have multiple separate directives of the same type on a page? Since they share a common API (singleton), the state is also shared. Therefore, i ...

Ways to implement distinct values for model and input field in Angular 5

I'm currently working on an Angular 5 application and I have a requirement to format an input field with thousand separators (spaces). However, the model I am using only allows numbers without spaces. Since my application is already fully developed, ...

Enhancing the Rendering of React's props.children

I have set up my code like this: // Parent.js class Parent extends React.Component { render() { return { this.props.children } } } // Child.js class Child extends React.Component { render() { let message; const greet = ...

What is the process for including a class on a div element?

I have written a code that displays a series of images in a sequence. Once the last image appears, I want to switch the class from .d-none to .d-block on the div Can this be achieved? onload = function startAnimation() { var frames = document.getE ...

What causes the error message 'avoid pushing route with duplicate key' when using NavigationStateUtils in React Native?

Within my React Native + Redux project, I have set up a reducer for navigation utilizing NavigationStateUtils: import { PUSH_ROUTE, POP_ROUTE } from '../Constants/ActionTypes' import { NavigationExperimental } from 'react-native' impo ...

Sending a websocket post request to a NODE server and receiving no response

I'm in the process of setting up a node server to act as an intermediary for my website. I am utilizing several libraries for this purpose. Axios - used for making requests to the API and fetching data from the database. Socket.io - employed to track ...

Script in Javascript halting Internet Explorer's operation

I'm encountering a problem with Internet Explorer freezing due to the following code. This code is part of a project that focuses on handling student grades: var array1 = StudentGradeAreadHugeList(); var nextArrayItem = function() { var grade = ...

The datepicker in Angular UI is displaying incorrect dates

Currently, I am developing an application using Angular and incorporating Angular UI. One of the features I have implemented is a datepicker that is coded like this: <input type="text" ng-required="true" name="targetDate" uib-date ...

The busboy file size limit event is not triggering

I am currently in the process of uploading a file via Express to a MongoDb database. Everything is functioning properly, but now I am attempting to implement a size limit for the files. The busboy configuration is set as described on the busboy site: var ...

"Using nginx to proxy a Node.js Express application running on a remote server within a sub

I am facing a challenge where I need to host multiple node applications on a single server. To achieve this, I have set up the applications to run on different ports and can access them by specifying the IP address along with the respective port numbers. ...

Steps to create a toggle feature for the FAQ accordion

I am currently working on creating an interactive FAQ accordion with specific features in mind: 1- Only one question and answer visible at a time (I have achieved this) 2- When toggling the open question, it should close automatically (having trouble with ...