AxiosError: Request failed with status code 404 - Node.js, Express, React js, MySQL

Donny Lao

I'm trying to implement a registration and login system into my website with Axios performing a post request in React (Home.jsx) to my Express server file (database.js) where I retrieve info from my MySQL database. When I try to submit my input info on the website however, I receive this error: "AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}"

Axios Error

I've tried reading up on similar questions asked here and none of the responses have managed to work for me. From what I understand, I think the issue may be between my Axios post request using XML HTTP requests while Express is made on top of the HTTP module, meaning the endpoint for my Axios post request doesn't actually exist to retrieve the info. That said, I am unsure how to implement this correction so that the code will work. Here is my code in question:

My frontend React component on Home.jsx:

import React, { useState, useEffect } from "react";
import { Header } from "./components/homePage/header";
import { Features } from "./components/homePage/features";
import { About } from "./components/homePage/about";
import { Location } from "./components/homePage/location";
import { Programs } from "./components/homePage/programs";
import { Gallery } from "./components/homePage/gallery";
import { Team } from "./components/homePage/Team";
import JsonData from "./data/data.json";
import SmoothScroll from "smooth-scroll";
import axios from "axios";
import "./Home.css";

//const instance = axios.create();

export const scroll = new SmoothScroll('a[href*="#"]', {
  speed: 1000,
  speedAsDuration: true,
});

const Home = () => {
  const [landingPageData, setLandingPageData] = useState({});
  useEffect(() => {
    setLandingPageData(JsonData);
  }, []);

  const [emailReg, setEmailReg] = useState("");
  const [passwordReg, setPasswordReg] = useState("");

  const register = () => {
    const data = {email: emailReg, password: passwordReg};
    axios.post("http://localhost:3000/register", data).then((response) => {
      console.log(response.data);
    });
  };

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const login = () => {
    const data = {email: email, password: password};
    axios.post("http://localhost:3000/login", data).then((response) => {
      console.log(response.data);
    });
  };

  return (
    <div>
      <h1>Registration</h1>
      <label>Email: </label>
      <input type="text" onChange={(e) => {
        setEmailReg(e.target.value);
        }} 
      />
      <label>Password: </label>
      <input type="text" onChange={(e) => {
        setPasswordReg(e.target.value);
        }} 
      />
      <button onClick={register}>Register</button>

      <h1>Login</h1>
      <label>Email: </label>
      <input type="text" onChange={(e) => {
        setEmail(e.target.value);
        }} 
      />
      <label>Password: </label>
      <input type="text" onChange={(e) => {
        setPassword(e.target.value);
        }} 
      />
      <button onClick={login}>Login</button>

      {/*````````````````````````*/}
      <Header data={landingPageData.Header} />
      <Features data={landingPageData.Features} />
      <About data={landingPageData.About} />
      <Location data={landingPageData.Location} />      
      <Programs data={landingPageData.Programs} />
      <Gallery data={landingPageData.Gallery}/>
      <Team data={landingPageData.Team} />
    </div>
  );
};

export default Home;

My backend Express server.js file

const express = require("express");
const mysql = require("mysql2");
const cors = require("cors");

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

const PORT = process.env.PORT || 3001;

app.listen(PORT, () => {
    console.log(`Server is listening on port ${PORT}`);
});

const connection = mysql.createConnection({
    user: "root",
    host: "localhost",
    password: "CicadaCode@7",
    database: "lkmadb",
});

app.post("/register", async (req, res) => {

    const email = req.body.email;
    const password = req.body.password;

    connection.query("INSERT INTO account (email, password) VALUES (?,?)", 
    [email, password], (err, result) => {
        if (err) {
            console.log(err);
        }
        res.send(result);
        res.send("registeration successful");
    });
});

app.post("/login", async (req, res) => {

    const email = req.body.email;
    const password = req.body.password;
    
    connection.query("SELECT * FROM account WHERE email = ? AND password = ?",
    [email, password], (err, result) => {
        if (err) {
            res.send({err: err});
        } 
            
        if (result) {
            res.send(result);
            res.send({message: "You logged in"});
        } else {
            res.send({message: "Wrong combination"});
        }       
    });
});

lpizzinidev

Make sure that you are making the request to the correct port:

axios.post("http://localhost:3001/register", data)

Also, as @rantao suggested, you should send the result just once:

app.post("/register", async (req, res) => {

    const email = req.body.email;
    const password = req.body.password;

    connection.query("INSERT INTO account (email, password) VALUES (?,?)", 
    [email, password], (err, result) => {
        if (err) {
            console.log(err);
        }
        res.status(200).send("registeration successful");
    });
});

If you need to respond with multiple properties you should use json:

res.status(200).json({ message: "registeration successful", result });

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Update on submitting form in React - AxiosError: Request failed with status code 404

Uncaught (in promise) AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST' :(

AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST'

I'm getting a ERROR Request failed with status code 404 AxiosError: Request failed with status code 404

Unhandled Runtime Error AxiosError: Request failed with status code 401 in next.js

Axios always return [AxiosError: Request failed with status code 400]

Spring boot and React JS: Uncaught (in promise) Error: Request failed with status code 404

Uncaught (in promise) AxiosError in React JS

React and Express iTunes Search API :: Error: Request failed with status code 404

Error status: 404 returned with PUT request using Node.js (express), Angular, and MongoDB

How to fix, "Error: Request failed with status code 404" in axios Next js

React Native Expo Request failed with status code 404

React - axios.post error 'Request failed with status code 404'

Request failed with status code 404 (React Native, Axios)

StatusCode:: 500, AxiosError:: Request failed with status code 401 Error[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Error 404 in react native using axios - Request failed with status code 404

Node express 404 error HTTP status code

Node.js / Intellij: http post request returns code 404

Failed to connect react to backend node js server express

react-native axios.get() [Error: Request failed with status code 404]

Uncaught (in promise) Error: Request failed with status code 400, How can I solve this error in React.js + Django App?

React Native Request failed with status code 400

Request failed with status code 423 - React Project

Request failed with status 403, react-native-screens.js, react-native-stack.js

Node JS + Express - Asynchronous request

How to request react app over internet with express/node.js

Failed to load resource: the server responded with a status of 404 (Not Found) when editing form React Node MySQL

Firebase Cloud Function Keep return "Request failed with status code 404"

Axios catch error Request failed with status code 404

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive