【问题标题】:POST Request: How to read req.body from formPOST 请求:如何从表单中读取 req.body
【发布时间】:2021-03-28 11:55:17
【问题描述】:

我使用 POSTMAN 来了解 API 请求的工作原理,但现在我不知道如何将它与我的前端集成。 如何从请求正文中获取数据?

我的index.ejs 文件中有以下内容:

<form action="/items" method="post">
    <input class="form-control" id="user-input" type="text" maxlength="50" placeholder="Add an item to shopping list" name="input">
    <span class="input-group-btn">
        <button class="btn btn-default btn-group-sm" id="add-button" type="submit">ADD</button>
    </span>
</form>

我需要在上面的输入框中获取用户输入的内容。这是我在app.js 文件中的内容:

const bodyParser = require('body-parser');
var jsonParser = bodyParser.json();

app.post('/items', jsonParser, (req, res) => {
    if(items.includes(req.body.input)){
        console.log("Item already exists!");
    } else {
        items.push(req.body.input);
        console.log("Item added");
        console.log(items);
    }
    res.redirect('/');
});

POST 请求正常工作,但添加的项目是 undefined,如果我从 req.body 中删除 .input,项目是 [object Object]

我做错了什么,或者我应该做些什么不同的事情?

【问题讨论】:

  • 表单发送数据时,发送的不是JSON,而是application/x-www-form-urlencoded。尝试使用bodyParser.urlencoded({ extended: false })(或者代替bodyParser.json(),或者如果你仍然想接受JSON,也可以使用它)
  • @blex:明白了!现在可以了,非常感谢:)

标签: javascript node.js json rest ejs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-16
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多