簡體   English   中英

AxiosError:請求失敗,狀態代碼為 404 - Node.js,Express,React js,MySQL

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

我正在嘗試使用 Axios 在我的網站中實施注冊和登錄系統,在 React (Home.jsx) 中向我的 Express 服務器文件 (database.js) 執行發布請求,我從 MySQL 數據庫中檢索信息。 但是,當我嘗試在網站上提交我的輸入信息時,我收到此錯誤:“AxiosError {消息:'請求失敗,狀態代碼 404',名稱:'AxiosError',代碼:'ERR_BAD_REQUEST',配置:{...},請求:XMLHttpRequest,...}”

Axios 錯誤

我已經嘗試閱讀此處提出的類似問題,但沒有任何回復對我有用。 據我了解,我認為問題可能出在我使用 XML HTTP 請求的 Axios 發布請求之間,而 Express 是在 HTTP 模塊之上創建的,這意味着我的 Axios 發布請求的端點實際上並不存在以檢索信息。 也就是說,我不確定如何實施此更正以使代碼正常工作。 這是我的問題代碼:

我在 Home.jsx 上的前端 React 組件:

 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;

我的后端 Express server.js 文件

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

確保您向正確的端口發出請求:

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

另外,正如@rantao 所建議的,您應該只send一次結果:

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

如果您需要使用多個屬性進行響應,您應該使用json

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM