【问题标题】:Form in html nodejs returns undefined after receiving post requesthtml nodejs中的表单在收到post请求后返回未定义
【发布时间】:2021-03-23 18:18:22
【问题描述】:

我在 HTML 中做了一个 <form></form> 对象,它应该返回用户名、电子邮件和密码,但由于某种原因,如果我执行 req.body.name 或其他任何操作,它会返回 undefined,它只是无法正常工作并且不知道为什么

这是我的 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() 方法需要一个字符串)

【问题讨论】:

    标签: html node.js forms


    【解决方案1】:

    发生这种情况是因为您可能没有使用body-parser。您应该使用服务器入口点中的中间件来解析请求的正文。 另外,你的问题是重复的,你可以找到完整的答案here

    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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 2021-01-05
      • 1970-01-01
      • 2017-07-14
      • 2021-01-28
      • 1970-01-01
      • 2018-03-22
      相关资源
      最近更新 更多