nodejs不会在req.body.blog中发送任何数据

时间:2017-09-05 16:07:33

标签: javascript node.js mongodb express

我正在从web开发人员bootcamp创建这个博客应用程序,我在这个错误中遇到了创建新博客的表单没有将任何数据发送回数据库并且数据库将其保存为空。我正在使用mongodb,当我看到我的数据库时,它正在存储空对象。这是app.js的代码

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

mongoose.connect("mongodb://localhost/restful", {
useMongoClient:true
});

app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyparser.json());

// app.use(bodyparser.json({ type: 'application/vnd.api+json' }));
app.use(bodyparser.urlencoded({extended:true}));

//MONGOOSE MODEL CONFIG
//=================================
var blogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: Date //{type: Date, default : Date.now}

});

var blog = mongoose.model("blog" , blogSchema);

// blog.create([{
//     title: "test post",
// image : 
"https://imagejournal.org/wpcontent/uploads/2017/08/17140945161_586d5e98f7_o-600x300.jpg",
//     body : "This is the first post"
// },
// {
//   title: "second Post",
//   image: "https://images.pexels.com/photos/33109/fall-autumn-red-
season.jpg?h=350&auto=compress&cs=tinysrgb",
//   body: "this is a second post"
// }]
// );

//RESTful routes
//==========================================
//==========================================

//Home

app.get("/",function(req,res){
res.redirect("/blogs");
})
//NEW ROUTE

app.get("/blogs/new",function(req,res){
  res.render("new");
});

//CREATE ROUTE
 app.post("/blogs", function(req,res){
//create blogs
blog.create(req.body.blog, function(err, newblog){
if(err){
 console.log("This is if error " + err);
res.render("new");
}
else{
//then redirect to the INDEX
res.redirect("/blogs");
console.log("This is if no error " + req.body.blog + "  "+ err );
 }
});
});

//SHOW ROUTE
app.get("/blogs/:id", function(req,res){
 blog.findById(req.params.id, function(err,foundblog){
 if(err){
   res.redirect("/blogs");
 }
 else{
   res.render("show", {blog: foundblog});
 }
 });
});

//INDEX ROUTE
app.get("/blogs", function(req,res){
blog.find({}, function(err,blogs){
    if(err)
        {
            console.log("error");
        }
    else
        {
               res.render("index", {blogs:blogs});

        }
    })
});



//listening port

app.listen(3000,function(){
  console.log("Blog app running");
})

表单的代码是这样的:

<% include ./partials/header.ejs %>

<div class="ui main text container segment">
<div class="ui huge header">New Blog</div>
<form class="ui form" action="/blogs" method="POST">
<div class="field">
  <label>Title</label>
  <input type="text" name="blogtitle" placeholder="title">
</div>
<div class="field">
  <label>Image</label>
<input type="text" name="blogimage" placeholder="image">
</div>
<div class="field">
<label>Body</label>
<textarea name="blogbody" placeholder="Blog body goes here"></textarea>
</div>
<input class="ui inverted big olive button" type="submit" >
</form>

</div>

<% include ./partials/footer.ejs %>

现在控制台正在打印&#34;这是因为没有错误undefined null&#34;

现在我所做的就是通过了

blog.create({ name: req.body.blogtitle, image:req.body.blogimage, body: 
req.body.blogbody} , function(err, newblog){...});

这似乎有效但如果我在Schema中有很多参数,我是否必须逐个声明这个?在colt课程中,只需键入req.body.blog并说它包含所有数据。

请帮助我!

3 个答案:

答案 0 :(得分:0)

req.body的属性与name中输入字段的<form>属性相对应。 req.body.blogundefined,因为您没有name="blog"的输入元素。

尝试console.log - req.body查看其属性,以便了解要使用的属性。但根据您的<form>req.body只有blogtitleblogimageblogbody

答案 1 :(得分:0)

我认为你错过了输入名称。当您在服务器端代码上使用它时,它应该像blogtitleblogimageblogbodyreq.body填充如下:

 { blogtitle: 'your_blog_title',blogimage: 'your_blog_image',blogbody: 'your_blog_body' }

所以你必须像req.body.blogtitle

那样抓住它们
//CREATE ROUTE
app.post("/blogs", function(req,res){
//create blogs
blog.create(req.body.blogtitle, function(err, newblog){
if(err){
  console.log("This is if error " + err);
  res.render("new");
}
else{
//then redirect to the INDEX
  res.redirect("/blogs");
  console.log("This is if no error " + req.body.blogtitle + "  "+ err );
 }
});
});

答案 2 :(得分:0)

根据您的HTML输入,您将获得req.body之类的内容:

{ 
    blogtitle: 'your_blog_title',
    blogimage: 'your_blog_image',
    blogbody: 'your_blog_body' 
}

因此,您必须在下面的代码中为每个模型和每个字段使用它。

blog.create({
    name: req.body.blogtitle,
    image: req.body.blogimage, 
    body: req.body.blogbody
},function(err, newblog){...});

但如果你想直接使用

// validate req.body.blog
blog.create(req.body.blog, function(err, newblog){...});

然后您必须定义html类似model[field]的内容,下面是示例代码。

<form class="ui form" action="/blogs" method="POST">
  <div class="field">
    <label>Title</label>
    <input type="text" name="blog[title]" placeholder="title">
  </div>
  <div class="field">
    <label>Image</label>
    <input type="text" name="blog[image]" placeholder="image">
  </div>
  <div class="field">
    <label>Body</label>
    <textarea name="blog[body]" placeholder="Blog body goes here"></textarea>
  </div>
  <input class="ui inverted big olive button" type="submit" >
</form>

请注意直接使用req.body.blog;你必须给html输入提供相同的字段(列名)。