JavaScript 检查后提交 HTML 表单 节点 Js req.body 内容将未定义
HTML form submit after javascript check Node Js req.body content will undefined
我遇到了一个问题,当我的html表单提交时,Node Js app.post{}将获得正确的值。但是,当我在表单中使用onsubmit并在提交之前检查值时。然后节点 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>
节点.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
});
如果您的用户名和密码正确,您的函数 checklogin(在客户端 js 代码中)不会返回任何内容,您必须在其中添加返回
并在您的 HTML 输入中添加一个 ID(用户名和密码)
已更新。
既然你已经更新了这个问题,我建议你这样做:
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;
}
}
相关文章:
- 节点.js快速删除 req.body 不起作用
- 在node.jsexpress应用程序中,req.body没有得到<text区域>价值
- 如何从未定义的表单中获取req.body
- post-router的req.body包含新行和冒号
- req.body使用MEAN Express 4.x和Node.js未定义
- 如何在js源节点上将数组作为req.body发送
- Sails.js req.files为空,req.body.image未定义
- 从中间件通过 req.body 传递变量
- express.js req.body 始终为空
- Reactjs req.body shows [object Object]
- req.body 没有给出这个名字
- 无法确定 req.body.name 的值 - 快速节点 JS
- 隐藏/禁用字段从 req.body 中消失(Express JS bodyParser)
- 将 req.body 属性复制到猫鼬模型中时出错
- Express 4 Multer / req.body 和 res.json 未定义
- 节点.JS req.body 字符串太长
- Express API - 验证 req.body 元素
- Nodejs - Req.body 未定义在 post 中,带有快速 4.9.0
- 我无法从nodejs + expressjs中的req.body获取数据
- Express Multer 文件上传 req.body 和 req.file 未定义