Node.js+Express.js+MySQL登录页点击提交出现Cannot POST /login错误
解决「Cannot POST /login」错误及登录逻辑问题
核心问题分析与修复步骤
1. 服务器运行方式错误
你使用lite-server运行Node.js服务器,但lite-server是静态文件服务器,仅能处理静态资源请求,无法识别Express定义的POST /login路由,这是触发「Cannot POST /login」错误的根本原因。
解决:直接运行你的Express服务器文件(script.js),而非lite-server。安装完所有依赖后,执行:
node script.js
之后访问http://localhost:3000(该端口为你Express代码中监听的端口)。
2. 代码中的关键错误修复
(1)移除无效冗余代码
- 删掉重复调用的
connection.connect();(保留带回调的那一次即可) - 删掉未定义
query的提前查询代码块:
connection.query(query, (error, results) => { if (error) { console.error(`Error executing the query: ${error.stack}`); return res.status(500).send({ error }); } });
- 删掉无用的
router.post('/login');(你已通过app.post('/login')定义路由,且未挂载该router)
(2)托管静态文件
Express需通过express.static托管HTML、CSS等静态资源,否则无法访问index.html和layout.html。添加以下代码:
// 假设静态文件都在当前目录,可根据实际路径调整 app.use(express.static('.'));
(3)修复前端页面错误
index.html中无需引入服务器端的script.js(浏览器无法运行Node.js模块),删掉该行:
<script nonce="randomvalue" src="script.js"></script>
(4)避免SQL注入风险
不要用字符串拼接生成SQL语句,改用MySQL参数化查询:
const query = 'SELECT * FROM users WHERE UserName = ? AND UserPass = ?'; connection.query(query, [username, password], (error, results) => { // 原有逻辑 });
修正后的完整代码
script.js
import express from 'express'; const app = express(); import { createConnection } from 'mysql'; import bodyParser from 'body-parser'; // 创建MySQL连接 const connection = createConnection({ host: 'localhost', user: 'pablo', password: 'KotWButach!', database: 'logowanie' }); // 连接MySQL服务器 connection.connect((err) => { if (err) { console.error(`数据库连接错误: ${err.stack}`); return; } console.log(`已连接数据库,线程ID: ${connection.threadId}`); }); // 解析请求体 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); // 托管静态文件 app.use(express.static('.')); // 登录路由处理 app.post('/login', (req, res) => { const { username, password } = req.body; // 参数化查询,防止SQL注入 const query = 'SELECT * FROM users WHERE UserName = ? AND UserPass = ?'; connection.query(query, [username, password], (error, results) => { if (error) { console.error(`数据库查询错误: ${error.stack}`); return res.status(500).send({ message: '服务器内部错误' }); } if (results.length === 0) { return res.status(401).send({ message: 'Invalid username or password' }); } // 验证通过,重定向到layout.html res.redirect('/layout.html'); }); }); app.listen(3000, () => { console.log('服务器运行在端口3000'); });
index.html
<!DOCTYPE html> <html> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'nonce-randomvalue'"> <head> <link rel="stylesheet" type="text/css" href="styles.css"> <title>Login</title> </head> <body> <form action="/login" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username"> <br> <label for="password">Password:</label> <input type="password" id="password" name="password"> <br><br> <input type="submit" value="Submit"> </form> </body> </html>
验证步骤
- 确保MySQL服务正在运行,
logowanie数据库的users表存在且有测试数据; - 安装依赖(若未安装):
npm install express mysql body-parser
- 运行服务器:
node script.js; - 访问
http://localhost:3000/index.html,输入正确/错误凭据测试登录逻辑。
内容的提问来源于stack exchange,提问作者Paweł Owczarek
相关产品推荐
相关产品推荐

