提交新用户信息时出现TypeError与500内部服务器错误,求排查
注册功能报错排查与解决方案
遇到的问题
- 报错:
TypeError: Cannot read properties of undefined (reading 'email') - 后端返回:
POST http://localhost:3001/signin 500 (Internal Server Error) - 前端捕获异常:
Uncaught (in promise) AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', ...}
错误原因分析
- Express未启用JSON解析:后端server中使用
app.use(express()),未配置JSON请求体解析,导致req.body为undefined,读取req.body.email时触发类型错误。 - Mongoose Schema定义错误:userModel里的字段类型写成空字符串
'',未指定正确的数据类型(如String),Mongoose无法正常处理数据存储。 - 后端路由未处理数据库操作的响应与异常:
newUser.save()未添加then/catch逻辑,既不返回成功响应,也不捕获存储错误,导致请求超时触发500错误。 - 前端代码缺失依赖导入与输入绑定:未导入
useState钩子;第一个密码输入框未绑定onChange、name和value,无法同步用户输入。 - 前端未处理Axios请求异常:
axios.post仅处理成功回调,未捕获错误,导致500错误时抛出未处理的Promise异常。
解决方案
1. 修复后端Server的JSON解析配置
修改/server代码,启用JSON请求体解析,并添加MongoDB连接异常捕获:
const app = express() const cors = require("cors") const mongoose = require("mongoose") app.use(cors()) app.use(express.json()) // 替换原express(),启用JSON解析 // 连接MongoDB并捕获异常 mongoose.connect("mongodb+srv://daw_dzieniszewski:******@cluster0.mn9uw.mongodb.net/firma_edukacyjna") .then(() => console.log("MongoDB连接成功")) .catch(err => console.log("MongoDB连接失败", err)) // 挂载路由 app.use("/", require("./backend/routes/userRoute")) app.listen(3001, function (){ console.log("express server is running on port 3001") })
2. 修正Mongoose User Schema定义
修改/userModel,指定字段类型并添加必填验证:
const mongoose = require("mongoose") const Schema = mongoose.Schema const userSchema = new Schema({ email: { type: String, required: true, unique: true }, password: { type: String, required: true } }) const User = mongoose.model("User", userSchema) module.exports = User;
3. 完善后端路由的响应与异常处理
修改/userRouter,使用async/await处理数据库操作,返回正确响应:
const router = express.Router() const User = require("../models/userModel") router.route("/signin").post(async (req, res, next) =>{ try { const { email, password } = req.body; const newUser = new User({ email, password }); const savedUser = await newUser.save(); res.status(201).json({ message: "注册成功", user: savedUser }); } catch (err) { res.status(500).json({ message: "注册失败", error: err.message }); next(err); } }) module.exports = router;
4. 修复前端代码的缺失项
修改/SigninC,补全useState导入与密码输入框绑定,添加Axios错误捕获:
import {Container} from "react-bootstrap" import axios from "axios"; import { useState } from "react"; // 补全useState导入 function SignInC() { const [input, setInput] = useState({ email: '', password: '' }) function handleChange(event) { const {name, value} = event.target; setInput(prevInput => ({ ...prevInput, [name]: value })); } function handleClick(event) { event.preventDefault(); axios.post('http://localhost:3001/signin', input) .then(response => console.log("注册成功", response)) .catch(err => console.log("注册失败", err)); // 捕获请求异常 } return ( <div className="p-5 m-3 d-sm-flex"> <Container className="container-sm w-auto p-5 border rounded-4 bg-light"> <div> <form> <div className="mb-4"> <label htmlFor="InputEmail" className="form-label fs-4">Email address</label> <input onChange={handleChange} name="email" value={input.email} type="email" className="form-control form-control-sm" id="exampleInputEmail1" /> </div> <div className="mb-4"> <label htmlFor="InputPassword1" className="form-label fs-4">Password</label> <input type="password" className="form-control" id="exampleInputPassword1" onChange={handleChange} name="password" value={input.password} /> </div> <div className="mb-4"> <label htmlFor="InputPassword2" className="form-label fs-4">Repeat password</label> <input onChange={handleChange} value={input.password} name="password" type="password" className="form-control" id="exampleInputPassword2" /> </div> <button onClick={handleClick} type="submit" className="btn btn-primary">Sign In</button> </form> </div> </Container> </div> ); } export default SignInC;
内容的提问来源于stack exchange,提问作者Raylle
相关产品推荐
相关产品推荐

