[英]HTML form submit after javascript check Node Js req.body content will undefined
I got a problem, when my html Form submit, Node Js app.post{} will get correct value. 我遇到了一个问题,当我提交html表单时,Node Js app.post {}将获得正确的值。 However, when I use onsubmit in the form, and check value before submit.
但是,当我在表单中使用onsubmit并在提交之前检查值时。 Then Node Js app.post req.body will display undefinded.
然后,Node Js app.post req.body将显示为未定义。
Original code: html: 原始代码: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: 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
});
however I want check value that input in form then submit, therefore, I update the form code like below: 但是我想检查在表单中输入的值然后提交,因此,我更新如下表单代码:
html: 的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>
my node js: 我的节点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
});
Updated. 更新。
Since you have updated the question, i would suggest you this: 既然您已经更新了问题,我建议您这样做:
onsubmit="return checkLoginInfo(this)" <!-- pass the form here -->
Now in the js function: 现在在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;
}
}
If your username and password are correct your function checklogin (in the client js code ) doesn't return anything you'll have to add a return in it 如果您的用户名和密码正确,则函数checklogin(在客户端js代码中)不会返回任何内容,您必须在其中添加返回值
and also add an id to your html inputs ( username and password ) 并在您的html输入中添加一个ID(用户名和密码)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.