簡體   English   中英

req.body 中的 Express.js“TypeError:無法讀取未定義的屬性”

[英]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>

`

我剛開始學習 express,但已經遇到問題,而且我找不到任何修復方法。 req.body 變量在帖子中不知何故未定義。 這將是一個登錄系統。 (對不起,我的英語不好)

我首先嘗試在 github 上這樣做: https://github.com/WebDevSimplified/express-crash-course但我的控制台中仍然出現“TypeError:無法讀取未定義的屬性”錯誤。 所以我正在尋找其他東西並找到了這個: https://codeshack.io/basic-login-system-nodejs-express-mysql/我的代碼基於 codeshack 示例,但我仍然遇到錯誤。

在處理程序之前添加中間件

app.use(bodyParser.urlencoded({ extended: false }))

如果你想訪問 post 請求的主體,我們需要使用 express 中間件來解析請求的主體,並將其附加到req.body object 下。
為此,我們可以使用express.urlencoded()中間件。 更多信息鏈接

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM