繁体   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