繁体   English   中英

javascript检查Node Js req.body内容后未提交HTML表单

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

我遇到了一个问题,当我提交html表单时,Node Js app.post {}将获得正确的值。 但是,当我在表单中使用onsubmit并在提交之前检查值时。 然后,Node 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>

node.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


});

更新。

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

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;
  }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM