简体   繁体   中英

nodejs form not sending any data back in req.body.blog

I am creating this blog app from web developer bootcamp annd i am struck in this error where the form to create new blog is not sending any data back to the database and the database is saving it empty. i am using mongodb and when i see my database it is storing empty objects. here is te code for 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");
})

And the code for the form is this :

<% 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 %>

Now the console is printing " This is if no error undefined null "

now what i did is i passed

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

this seems to be working but if I had many parameter in Schema should i have to declare this one by one? In the course colt just typed req.body.blog and said that it contains all the data.

Please help me!

According to your HTML inputs you will get the req.body like:

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

Hence you have to use it in the code below for every model and every field.

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

But if you want to just use directly

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

then you would have to define you html something like model[field] , sample code below.

<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>

Please notice in order to use req.body.blog directly; you have to give the same field(column name) to the html inputs.

The properties of req.body corresponds to the name attributes of the input fields in your <form> . req.body.blog is undefined because you don't have an input element with name="blog" .

Try console.log -ing req.body to see its properties so that you know which properties to use. But basing on your <form> , req.body would only have blogtitle , blogimage and blogbody .

I think your missed the input names. It should be like blogtitle , blogimage and blogbody when you use it on your server side code. req.body is populated like this:

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

So you have to grab them like 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 );
 }
});
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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