Search code examples
node.jsexpressejs

Express.js "TypeError: Cannot read properties of undefined" in req.body


`

router.post("/login", (req, res) => {
    console.log(req.body.username)
    console.log(req.body.password)
    
    res.redirect("/")
})

<body>
    <form action="/register" method="post">
        <label for="username">

        </label>
        <input type="text" name="username" placeholder="Username" id="username" required>
        <label for="password">
            <i class="fas fa-lock"></i>
        </label>
        <input type="password" name="password" placeholder="Password" id="password" required>
        <input type="submit" value="Login">
    </form>
</body>

`

I just started learning express but already have a problem and I can't find any fixes. Somehow the req.body variable is undefined in the post. This is going to be a login system. (Sorry for my bad english)

I first tried to do it like here on github: https://github.com/WebDevSimplified/express-crash-course but i still had the "TypeError: Cannot read properties of undefined" error in my console. So I was looking for something else and found this: https://codeshack.io/basic-login-system-nodejs-express-mysql/ My code is based on the codeshack example but I'm still getting the error.


Solution

  • If you want to access body of post request, we need to use express middleware which will parse the body of request and it will attached it under req.body object.
    In order to do it we can use express.urlencoded() middleware. for more information link

    router.post("/login",express.urlencoded({ extended: true }) , (req, res) => {
        console.log(req.body.username)
        console.log(req.body.password)
        res.redirect("/")
    })