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

Lambda function failing to execute Auth0 methods through the Auth0 node-auth0 SDK

I am working with a lambda function that triggers when a message is added to the SQS queue. Within the message, there is a userId that I want to connect to using the Auth0 node SDK. The code snippet for my GetUserDetails function below shows that it logs ...

Show the button's value in the textbox and update the selected button's color using JavaScript

I am having difficulty changing the background color of a selected button after displaying its value in a textbox. The code below successfully displays the button value in the textbox, but I can't figure out how to change the background color of the s ...

Issue with PG npm package's exception handling functionality is not functioning as expected

After installing "pg": "^8.0.2" and setting up the database.js file with database credentials, I noticed that no matter the issue, it never seems to enter the catch block to display errors. Instead, it always logs connected to the database. Can anyone help ...

Angularjs: a powerful tool for passing data efficiently between controllers

In my angular.js application, I have implemented multiple views and I am in need of maintaining the status across view changes. To achieve this, I have created a simple factory to share data between controllers. Instead of using "$scope" in the controllers ...

Issue with implementing MUI Style Tag in conjunction with styled-components and Typescript

I have created a custom SelectType component using Styled Components, which looks like this: import Select from '@mui/material/Select'; export const SelectType = styled(Select)` width:100%; border:2px solid #eaeaef; border-radius:8px ...

MUI-Datatable: Is there a way to show the total sum of all the values in a column at once

I have a column displaying the Total Amount, and I am looking for a way to show this totalAmount. After conducting some research, it seems like onTableChange is the key. Currently, it effectively displays all of the data using console.log("handleTab ...

Refreshing the value of multiple radio buttons and sending them via AJAX

I have a group of radio buttons here. <input class='required' type='radio' name='Tbl' id='get_this1' value='tbl_a'> <input class='required' type='radio' name='Tbl' id ...

Unleashing the Power of Dynamic JSON Data Access

I am facing an issue with my React Child component. Here is the code snippet: const SingleProject =(props)=>{ let data = projectData.VARIABLE_FROM_PROPS.projectDetails; let asideData = projectData.VARIABLE_FROM_PROPS.projectSideBar; useEffe ...

What is the destination of next(err) in Express when managing an error?

http://expressjs.com/guide/error-handling.html function logErrors(err, req, res, next) { console.error(err.stack); next(err); } This excerpt can be found in the expressJS documentation. I am curious to know what exactly happens after calling next ...

Is SSG the best approach for deploying a Nuxt.js dashboard?

We have plans to create an internal dashboard utilizing Nuxt.js. Since this dashboard will be used internally, there is no requirement for a universal mode. Typically, most dashboards are designed as SPAs (Single Page Applications). However, SPAs still ne ...

Issue with Nodejs Express redirection functionality

After clicking the login button, I encountered an issue where the page was not redirecting to the success screen despite all functionality seeming to work fine. Searching online for potential solutions proved fruitless. Update: The problem seems to stem f ...

Troubleshooting random array issues in JavaScript and jQuery

I want to create a randomized array with DOM elements, here's what I have so far: var allTargets=$('#target1, #target2, #target3, #target4'); var randomTargets=null; randomTargets = allTargets[Math.floor(Math.random() * allTargets.length)]; ...

onpageshow event behaves as expected exclusively on webkit browsers (triggers function solely when visible on the screen)

I am inserting an HTML file using an object tag. The encompassing div of the object tag is hidden with a display:none property. However, I encounter an issue where the onpageshow event that I placed on the body tag of the HTML object behaves differently a ...

The use of url.resolve() function with greater than two arguments

Currently, I'm utilizing the url.resolve() function to combine components of a URL from a configuration file in this manner: var uri = url.resolve(config.baseUrl, this.orgId, this.appId, type) However, it appears that using more than two arguments d ...

Passing backend variables/data to AngularJS in Express JS

As a newcomer to express js, I appreciate your patience with me. I've been diving into "MEAN Web Development" by Amos Q. Haviv and finding it to be an excellent read. However, there's one part that's leaving me puzzled. It seems that in or ...

Creating pages or tabs within a table using HTML5 and Angular is a simple and effective way to organize

I have a REST response that returns around 500 records. These records are being displayed in an Angular table. I would like to add customization options for the user, allowing them to choose to display 10/20/30... records per page. Additionally, I want to ...

Tips for managing the second datepicker for the return journey on Abhibus using Selenium webdriver

I am currently working on a code to choose departure date and return journey date, but I am encountering an issue where the return journey date is not being selected. The driver seems to be skipping over the return date selection and proceeding directly to ...

Changing the Div heights in Material UI with grid layout customization

I have a project that requires me to implement material-ui. Is there a way I can adjust the width and height of the div containing the "Sign In With" text (as shown in the first image) to bring the buttons closer to the text? Transformation from this: ht ...

React.js, encountering unusual behavior while implementing a timer

I'm currently working on a React project to create a basic timer. The start button should initialize the timer, while the stop button should pause it. However, I've encountered some unexpected behavior. When I click on start for the first time, ...

Utilizing $.getJSON to initiate a selection change event

I'm currently working on implementing a feature that involves adding categories to a dropdown list using jQuery Ajax. The goal is to load subcategories when a particular option is selected. However, I've encountered an issue where the addition o ...