简体   繁体   English

AxiosError:请求失败,状态代码为 404 - Node.js,Express,React js,MySQL

[英]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.我正在尝试使用 Axios 在我的网站中实施注册和登录系统,在 React (Home.jsx) 中向我的 Express 服务器文件 (database.js) 执行发布请求,我从 MySQL 数据库中检索信息。 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, …}"但是,当我尝试在网站上提交我的输入信息时,我收到此错误:“AxiosError {消息:'请求失败,状态代码 404',名称:'AxiosError',代码:'ERR_BAD_REQUEST',配置:{...},请求:XMLHttpRequest,...}”

Axios Error Axios 错误

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.据我了解,我认为问题可能出在我使用 XML HTTP 请求的 Axios 发布请求之间,而 Express 是在 HTTP 模块之上创建的,这意味着我的 Axios 发布请求的端点实际上并不存在以检索信息。 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:我在 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;

My backend Express server.js file我的后端 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"}); } }); });

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:另外,正如@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");
    });
});

If you need to respond with multiple properties you should use json :如果您需要使用多个属性进行响应,您应该使用json

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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