NodeJS Express req.body返回空字符串对象

时间:2019-11-27 15:05:51

标签: node.js express body-parser

我对nodeJS和express很陌生。我有一个我似乎无法解决的问题。

这是app.js

var express         = require("express"),
    app             = express(),
    mongoose        = require("mongoose"),
    bodyParser      = require("body-parser");

mongoose.connect("mongodb://localhost/to_do_app", {useNewUrlParser: true, useUnifiedTopology: true});
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));

// MODEL TODO
var todoSchema = new mongoose.Schema({
    title: String,
    created: {type: Date, default: Date.now}
});
var Todo = mongoose.model("Todo", todoSchema);

// Todo.create({
//     title: "Database To-Do Entry",
// });

// ROUTES
app.get("/", function(req, res){
    Todo.find({}, function(err, todos){
        if(err){
            console.log(err);
        } else {
            res.render("index", {todos: todos});
        }
    })
});

//CREATE ROUTE
app.post("/", function (req, res){
    Todo.create(req.body.todo, function(err, newToDo){
        if(err){
            console.log(err);
        } else {
            console.log("added" + newToDo)
        }
        console.log(req.body.todo);
    });
});

// START
app.listen(3000, function(){
    console.log("Server has started!");
});

index.ejs

<%- include("partials/header") %>

<div class="container my-5">
    <div class="row justify-content-center">
            <div class="card bg-dark" style="width: 18rem;">
                <div class="card-header text-white">
                    To-Do List
                    <a href="#collapseToDo" data-toggle="collapse"><i class="fas fa-plus ml-auto"></i></a>
                </div>

                <ul class="list-group list-group-flush">
                    <div class="collapse" id="collapseToDo">
                        <form action="/" method="POST">
                            <input class="list-group-item bg-light rounded-0" name="todo[title]" type="text" placeholder="Enter To-Do">
                        </form>
                    </div>
                    <% todos.forEach(function(todos){ %>
                    <li class="list-group-item"><%= todos.title %><span><i class="far fa-trash-alt"></i></span></li>
                    <% }) %>
                </ul>
            </div> 
    </div>
</div>

<%- include("partials/footer") %>

每次我运行此代码,然后尝试向数据库req.body.todo添加新的东西{Title:“”}。该字符串完全为空。我找不到解决此问题的方法。提前致谢。

1 个答案:

答案 0 :(得分:0)

您的错误是此行<input class="list-group-item bg-light rounded-0" name="todo[title]" type="text" placeholder="Enter To-Do">

输入字段的名称为todo[title],但是在您的服务器上,您尝试使用req.body.todo获取待办事项标题。

我认为您需要更新ejs文件,将输入名称设置为todo

<input class="list-group-item bg-light rounded-0" name="todo" type="text" placeholder="Enter To-Do">

我看到您CREATE ROUTE在创建待办事项后什么也不做。我认为,重定向到/路由会很好。

并且,如果您使用mongoose,那么Todo.create需要一个对象而不是字符串,我为Todo只需要title字段,那么路由最终将变为:

app.post("/", function (req, res){
    Todo.create({title: req.body.todo}, function(err, newToDo){ // object Todo
        if(err){
            console.log(err); // return to error page like res. render('error', {erro})
        } else {
            console.log("added" + newToDo)
            res.redirect('/') // reload the page
        }
        console.log(req.body.todo);
    });
});