路由已配置但请求返回404错误的技术求助
问题分析与解决
1. 404错误的核心原因:请求方法不匹配
后端代码中注册的是GET类型的/signup路由:
app.get("/signup", (req, res) => { // ... });
但前端发起的是POST请求:
await fetch("http://localhost:3001/signup", { method: "POST", // ... });
Express会严格按照请求方法+路径匹配路由,两者不匹配时就会返回404错误。
解决方法:修改后端路由为POST类型
将后端的app.get改为app.post:
app.post("/signup", (req, res) => { const { username, password } = req.body; res.json({ username: username, password: password }); console.log(username, password); });
2. 前端潜在的state更新错误
前端代码存在拼写错误:setUseranme应为setUsername,这会导致用户名输入框的内容无法正确同步到state中。
解决方法:修正拼写错误
修改前端的state声明和onChange事件:
const [username, setUsername] = useState(""); // ... onChange={(e) => setUsername(e.target.value)}
修改后的完整代码
后端index.js
const express = require("express"); const app = express(); const port = 3001; const cors = require("cors"); app.use(cors()); app.use(express.json()); app.post("/signup", (req, res) => { const { username, password } = req.body; res.json({ username: username, password: password }); console.log(username, password); }); app.listen(port, () => { console.log(`Server is running on port http://localhost:${port}`); });
前端SignupPage
import React, { useState } from "react"; const SignupPage = () => { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); async function handleSubmit(e) { e.preventDefault(); await fetch("http://localhost:3001/signup", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username, password }), }); } return ( <div> <h1>Signup Page</h1> <form onSubmit={handleSubmit}> <input type="text" placeholder="username" value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="off" /> <input type="password" placeholder="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="off" /> <button type="submit">Submit</button> </form> </div> ); }; export default SignupPage;
内容的提问来源于stack exchange,提问作者user16875752
相关产品推荐
相关产品推荐

