nodejs形式不发送回任何数据?

时间:2018-07-23 18:51:42

标签: node.js express mongoose

app.js

    var express = require('express');

    var app = express();

    var bodyParser = require('body-parser');

    var mongoose = require('mongoose');

    mongoose.connect('mongodb://localhost/my_app');

    app.use(express.static('public'));
    app.use(bodyParser.urlencoded({extended: true}));

    var blogSchema = new mongoose.Schema({

    title: String,

    image: String,

    body: String,

    created: {type: Date, default: Date.now}

});

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

    app.get('/',function(req,res){

       res.redirect('/blogs'); 

    });


    /*Blog.create({
       title: "Post 2",
        image: "https://www.photosforclass.com/download/pixabay-716579? 

 webUrl=https%3A%2F%2Fpixabay.com%2Fget%2Fee34b70a2ffd1c22d2524518b7444795ea76e5d00 
   4b0144297f3c77ea0eeb5_960.jpg&user=milivanily",
    body: "Garden"
});
*/

//index route

app.get('/blogs',function(req,res){

    Blog.find({},function(err,blogs){

        if(err)

            {

                console.log("Error");
            }
        else
            {
                res.render('index.ejs',{blogs:blogs}); 
            }
    });

});

//new route
app.get('/blogs/new',function(req,res){

   res.render('new.ejs'); 
});



app.post('/blogs',function(req,res){

  Blog.create(req.body.blog,function(err,newBlog){

    if(err)
    {
        res.render('new.ejs');
    }
    else
    {
        res.redirect('/blogs');
    }
  });

});



app.listen(5000,function(){

   console.log('Server has started!'); 
});

// new.ejs

        <div class="row form-group">
            <input type="text" name="blog[title]" placeholder="title" class="form-control">
        </div>

        <div class="row form-group">
            <input type="text" name="blog[image]" placeholder="image" class="form-control">
        </div>

        <div class="row form-group">
            <textarea class="form-control" name="blog[body]">
            </textarea>
        </div>


        <div class="row text-center">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>

0 个答案:

没有答案