I got a problem, when my html Form submit, Node Js app.post{} will get correct value. However, when I use onsubmit in the form, and check value before submit. Then Node Js app.post req.body will display undefinded.
Original code: 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
});
however I want check value that input in form then submit, therefore, I update the form code like below:
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:
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:
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
and also add an id to your html inputs ( username and password )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.