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

配置body-parser后req.body仍为undefined的问题求助

问题根源与解决方案

核心原因

你的表单使用了method="GET",浏览器处理GET请求时,会把表单数据编码到URL的查询字符串中,而非HTTP请求体里。body-parser中间件仅负责解析请求体内的数据,因此req.body会返回undefined,所有表单参数都存储在req.query对象里。

两种解决办法

办法1:修改服务器代码,从req.query获取参数

无需改动表单,直接将路由中的req.body替换为req.query即可:

app.get('/login', (req, res)=>{
    console.log(req.query.username);
    console.log(req.query.password_login);
    res.send("put tank in a mall");
});

办法2:改用POST请求(更推荐)

登录涉及敏感密码,GET请求会将密码暴露在URL、浏览器历史及服务器日志中,存在安全风险。建议改用POST:

  1. 修改表单的method属性:
<form action='/login' method="POST">
    <div class="input-field">
        <input type="text" name="username" placeholder="Enter your Username" value="asdasdas" required />
        <i class="uil uil-dialpad-alt icon"></i>
    </div>
    <div class="input-field">
        <input type="password" class="password" placeholder="Enter Password" name="password_login" value="asdasdas" required  />
       <i class="uil uil-lock icon"></i>
       <i class="uil uil-eye-slash eye"></i>
   </div>
   <div class="input-field button">
       <input type="submit" value="Login"/>
   </div>
</form>
  1. 将服务器的GET路由改为POST路由:
app.post('/login', (req, res)=>{
    console.log(req.body.username);
    console.log(req.body.password_login);
    res.send("put tank in a mall");
});

内容的提问来源于stack exchange,提问作者PP GODKING

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:50:33