簡體   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