JavaScript 检查后提交 HTML 表单 节点 Js req.body 内容将未定义

HTML form submit after javascript check Node Js req.body content will undefined

本文关键字:body req 未定义 Js 节点 检查 提交 HTML 表单 JavaScript      更新时间:2023-09-26

我遇到了一个问题,当我的html表单提交时,Node Js app.post{}将获得正确的值。但是,当我在表单中使用onsubmit并在提交之前检查值时。然后节点 Js app.post req.body 将显示未找到。

原始代码:.html:

<form id="formLogin" role="form" action="/loginprocess" method="POST">
  <input id="textEmail" name="username">
  <input id="textPwd" name="pwd">
  <button type="submit" id="btnLogin">login</button>
</form>

节点.js:

var express = require('express');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({     
  extended: true
}));
app.post('/loginprocess', function(req, res) {
    var username = req.body.username;
    var pwd = req.body.pwd;
    console.log("username=" + username);  //correct value
    console.log("pwd=" + pwd);            //correct value

});

但是我想要在表单中输入然后提交的检查值,因此,我更新表单代码,如下所示:

.html:

<form id="formLogin" role="form" action="/loginprocess" method="POST" onsubmit="return checkLoginInfo()">
  <input id="textEmail" name="username">
  <input id="textPwd" name="pwd">
  <button type="submit" id="btnLogin">login</button>
</form>
<script type="text/javascript">
function checkLoginInfo() {
    var username = document.getElementById("textEmail").value;
    var pwd = document.getElementById("textPwd").value;
    if ((username.length > 0) && (pwd.length > 0)) {
      console.log("yes");
     } else {
      console.log("no");
      return false;
     }
}
</script>

我的节点 JS:

var express = require('express');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({     
  extended: true
}));
app.post('/loginprocess', function(req, res) {
    var username = req.body.username;
    var pwd = req.body.pwd;
    console.log("username=" + username);  //undefined
    console.log("pwd=" + pwd);            //undefined

});

如果您的用户名和密码正确,您的函数 checklogin(在客户端 js 代码中)不会返回任何内容,您必须在其中添加返回

并在您的 HTML 输入中添加一个 ID(用户名和密码)

已更新。

既然你已经更新了这个问题,我建议你这样做:

onsubmit="return checkLoginInfo(this)"  <!-- pass the form here -->

现在在 js 函数中:

function checkLoginInfo(frm) { // <----get the form here
  var username = document.getElementById("textEmail").value;
  var pwd = document.getElementById("textPwd").value;
  if ((username.length > 0) && (pwd.length > 0)) {
    console.log("yes");
    frm.submit(); // <-----if valid just submit it here.
  } else {
    console.log("no");
    return false;
  }
}