You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ExpressJS登录功能报错Cannot POST /login,请求排查解决

解决ExpressJS中Cannot POST /login的问题

我帮你排查出几个关键问题,修正后就能正常处理登录请求了:

1. 路由定义存在语法错误

你的route.js里路由写法有个低级语法错误——router.post('/login')后面多了一个右括号,导致处理函数没有正确绑定到/login路由上。

修正后的route.js核心代码:

router.post('/login', (req,res)=>{ // 去掉多余的右括号
 var username= req.body.name;
 var password = req.body.password;
 // 注意:查询参数要放在数组里,避免SQL注入风险
 con.query('SELECT * FROM authentication WHERE username = ?', [username], function (error, results, fields) {
 if (error) {
 res.send({ "code":400, "failed":"error ocurred" })
 }else{
 if(results.length >0){
 if(results[0].password == password){
 res.send({ "code":200, "success":"login sucessfull" });
 } else{
 res.send({ "code":204, "success":"username and password does not match" });
 }
 } else{
 res.send({ "code":204, "success":"username does not exits" });
 }
 }
 });
})
module.exports = router

2. HTML表单缺少action属性

你的表单没有指定提交目标地址,默认会把请求发送到当前页面的URL(比如如果你的页面是/,就会POST到/),但你的登录路由是/login,服务器找不到对应路由就会抛出Cannot POST /login错误。

修正后的HTML表单:

<form method="POST" action="/login"> <!-- 添加action="/login"指定提交地址 -->
 <div class="container">
 <label for="uname"><b>Username</b></label>
 <input type="text" placeholder="Enter Username" name="name" >
 <label for="psw"><b>Password</b></label>
 <input type="password" placeholder="Enter Password" name="password">
 <button type="submit">Login</button>
 </div>
</form>

额外优化建议

  • 不要明文存储/比较密码:目前你直接用明文密码对比,存在严重安全风险,建议用bcrypt这类库对密码做哈希存储和验证。
  • 统一错误码:204代表无内容,用来表示登录失败不太合适,建议改用401(未授权)这类更贴合语义的状态码。

修正后重启服务器,提交表单应该就能正常触发/login的POST路由,处理登录逻辑了。

内容的提问来源于stack exchange,提问作者ana bel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:03:59