提交React注册表单后nodemon崩溃报PROTOCOL_CONNECTION_LOST如何解决
问题解决办法
问题根源
你当前使用mysql.createConnection()创建的是单例数据库连接,存在三个核心问题:
- 单连接有默认超时机制,MySQL服务端会主动断开长时间空闲/使用完成的连接,且没有自动重连逻辑,一次请求后连接断开就会抛出
PROTOCOL_CONNECTION_LOST错误导致服务崩溃 - 注册接口完成数据库操作后没有给前端返回响应,请求一直挂起也会加剧连接异常
- SQL语句里表名用了MySQL关键字
table,存在语法错误风险
具体修复步骤
1. 服务端替换单连接为连接池+补全响应逻辑
直接替换你的服务端代码为以下内容,将数据库连接改为连接池模式,连接池会自动管理连接复用、自动重连,同时补全接口响应:
const express = require("express"); const mysql = require("mysql"); const cors = require("cors"); const app = express(); app.use(express.json()); app.use(cors()); // 直接用cors中间件代替手写的跨域配置,更稳妥 // 改用连接池代替单连接 const db = mysql.createPool({ user: "你的数据库用户名", host: "你的数据库地址", password: "你的数据库密码", database: "你的数据库名", connectionLimit: 10, // 连接池最大连接数,按需调整 acquireTimeout: 30000, timeout: 60000 }); app.post('/register', (req, res) => { const {name, cpf, tel, email} = req.body; // 注意:表名table是MySQL关键字,建议改成user/register_users这类实际表名,必须用的话要加反引号`table` db.query("INSERT INTO `table` (name, cpf, tel, email) VALUES (?,?,?,?)", [name,cpf,tel,email], (err,result)=> { if(err) { console.log(err); return res.status(500).json({msg: "注册失败", error: err}) } res.status(200).json({msg: "注册成功", data: result}) } ) }); app.listen(3001, () => { console.log("running on port 3001") });
2. 前端修复表单默认提交问题
你的提交按钮是type="submit"放在form标签内,点击会触发页面默认刷新,修改register函数阻止默认行为:
const register = (e) => { e.preventDefault(); // 阻止form默认提交刷新 Axios.post('http://localhost:3001/register/', { name: name, cpf: cpf, tel: tel, email: email, }).then((response) => {console.log(response)}); };
form标签的action="#"可以删除,已经用axios提交不需要这个属性。
内容的提问来源于stack exchange,提问作者windside13
相关产品推荐
相关产品推荐

