首页 > 解决方案 > req.body 对于表单 GET 请求为空

问题描述

对于以下表格:

<div class = "container center_div" id="loginForm">

            <p> Enter username and password</p>
            <form action = "/authenticate" name="credentials" method="get">

                <div class="form-group">
                    <input type="text" class="form-control" name="username" id="username" placeholder="Username">
                </div>

                <div class="form-group">
                    <input type="password" class="form-control" name="password" id="password" placeholder="Password">
                </div>
                

                <button type="submit" class="btn btn-primary" id="loginCredentials">Log In</button>

            </form>

        </div>

在后端我有:

app.get("/authenticate", (req, res) => {
    console.log(req.body);
});

但是, req.body 是空的,我指定:

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

但是,它仍然是空的,我已经尝试设置extended:false,但这并不能解决它。有任何想法吗?

标签: htmlnode.js

解决方案


当您使用GET方法提交表单时,它会将表单数据以名称/值对的形式附加到 URL 中。这就是req.body对象为空的原因。此外,这也是您永远不应该对包含敏感数据的表单使用 GET 方法的原因之一。

使用POST方法,req.body 对象将有数据。


推荐阅读