简体   繁体   English

POST 请求:如何从表单中读取 req.body

[英]POST Request: How to read req.body from form

I have used POSTMAN to understand how API requests work, but now I don't know how to integrate that with my frontend.我已经使用 POSTMAN 来了解 API 请求是如何工作的,但现在我不知道如何将它与我的前端集成。 How do I get data from the request body?如何从请求正文中获取数据?

I have the following in my index.ejs file:我的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>

and I need to get what the user inputs in the input box above.我需要在上面的输入框中获取用户输入的内容。 This is what I have in my app.js file:这就是我的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('/');
});

The POST request is working-ish, but the added item is undefined and if I remove .input from req.body the item is [object Object] . POST 请求正常运行,但添加的项目undefined ,如果我从req.body中删除.input ,则项目为[object Object]

What am I doing wrong, or what should I do differently?我做错了什么,或者我应该做些什么不同的事情?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM