简体   繁体   中英

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

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"}); } }); });

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM