html - html nodejs中的表单在收到post请求后返回未定义
问题描述
我在 HTML 中做了一个<form></form>
对象,它应该返回用户名、电子邮件和密码,但由于某种原因,undefined
如果我这样做req.body.name
或其他任何事情,它就会返回,它只是无法工作,我知道为什么
这是我的 HTML 标记:
<div style="margin: auto; width: 400px; text-align: center; margin-top: 50px;" class="card">
<h1 class="loginTitle card-title" style="margin-top: 10px;">Register</h1>
<div class="card-body">
<form action="/register" method="POST">
<div>
<label class="loginLabel" for="name">Username: </label>
<input style="margin-left: 68px;" class="loginInput" id="name" name="name" required type="text">
</div>
<div>
<label class="loginLabel" for="email">Email: </label>
<input style="margin-left: 110px;" class="loginInput" id="email" name="email" required type="email">
</div>
<div>
<label class="loginLabel" for="password">Password: </label>
<input style="margin-left: 76px;" class="loginInput" id="password" name="password" required type="password">
</div>
<button type="submit" style="margin-top: 10px;">Register</button>
</form>
<a href="/login" style="margin-bottom: 10px; text-decoration: none; color: orange; font-size: 19px; margin-top: -10px;">Login</a>
</div>
</div>
这是我的 NodeJS 代码:
website.post('/register', async (req, res) => {
var usersReg = []
try {
const hashedPw = await bcrypt.hash(req.body.password, 10)
usersReg.push({
name: req.body.name,
email: req.body.email,
password: hashedPw
})
res.redirect('/login')
}
catch {
res.redirect('/register')
}
console.log(usersReg)
})
请帮助我 - 我不明白错误来自哪里。
(如果我不抓住它只是说该bcrypt.hash()
方法需要一个字符串)
解决方案
发生这种情况是因为您可能没有使用body-parser。您应该使用服务器入口点中的中间件来解析请求的正文。此外,您的问题是重复的,您可以在此处找到完整的答案。
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
推荐阅读
- database - 如何将初始数据插入 Mendix 数据库?
- python - 如何在 GraphQL 中表达输入验证
- c# - 垃圾收集器在 WeakReference 中删除(收集)对象的优先级是多少?
- css - 网格列的 margin-top
- c++ - QT - 如何在滚动区域上添加按钮(具有绝对位置)
- java - 为什么在单个参数 lambda 上添加括号会产生代码异味?
- javascript - Vue.js - 引导表更新消耗太多内存
- java - 使用泛型在java上查找重复项
- vue.js - 从 npm 打包的 vue 组件库传递/访问应用程序的服务
- css - 如何使 div 的高度等于 css 的身体高度?