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

时间:2016-07-13 09:31:35

标签: javascript node.js

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

原始代码: 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


});

2 个答案:

答案 0 :(得分:0)

已更新。

由于您已更新问题,我建议您:

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

答案 1 :(得分:0)

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

并为你的html输入(用户名和密码)添加一个id