0

I did in HTML a <form></form> object which should return a username, a email and a password, but for some reason it returns undefined if I do req.body.name or anything else and it just won't work and idk why

This is my HTML markup:

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

And this is my NodeJS code:

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

Please help me - I don't understand where the error is coming from.

(If I don't do catch it says just that the bcrypt.hash() method needs a string)

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
CodingFox
  • 43
  • 9

1 Answers1

3

This is happening because you are not probably using body-parser. You should use the middleware in your server entry point to parse the body of the requests. Also, your question is duplicated and you can find the complete answer 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())
Shayan
  • 238
  • 4
  • 11