2016-09-14 9 views
0

Javascript、NodeJS、MongoDB、Expressを使用更新するときに投稿がページに保存されないのはなぜですか?

私のアプリでは、ユーザーは入力フィールドを入力し、送信ボタンをクリックするとテキストがページに追加されます。私は正常にページにテキストを投稿することができますが、私はブラウザをリフレッシュすると、私の投稿は表示されません。私は私のpartials/test.ejsのスクリプトセクションでajaxを使ってリクエストを行う必要があると思いますが、これを実行する方法がわかりません。
モデル/ Blog.js

var 
    mongoose = require('mongoose'), 
    Schema = mongoose.Schema, 
    BlogSchema = new Schema({ 
    name: String 

}) 
var Blog = mongoose.model('Blog', BlogSchema) 
module.exports = Blog 

ビュー/パーシャル/ test.ejs

<body> 
<form> 
<button type="submit" class="btn btn-default pull-right" id="create">Submit</button> 
</form> 
<div class="feedback-messages"></div> 
</body> 

<script type="text/javascript"> 
var messages = $('.feedback-messages') 
var postItem = $("#create") 


postItem.on('click', function(evt) { 
evt.preventDefault(); 


    $.ajax({ 
    url: '/test', 
    method: 'POST', 
    contentType: 'application/json', 
    data: JSON.stringify({data: newItem}) 
    }) 
    .done(function(data) { 
     console.log("Hello"); 
     messages.append(newItem) 
}) 

ルート/ index.js

var 
    express = require('express'); 
    router = express.Router(); 
    bodyParser = require('body-parser'); 
    mongoose = require('mongoose'); 
    Blog = require('../models/Blog.js'); 
// route for home page 

router.get('/', function(req, res) { 
    res.render('./partials/home'); 
}); 

//route for test page 
router.get('/test', function(req, res) { 
res.render('./partials/test'); 
    }); 



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



router.get('/test', function(req, res){ 
    Blog.find({}, function(err, blog){ 
     if(err) return console.log(err) 
     res.json(blog); 
    }) 
}); 


router.post('/test', function(req, res){ 
    // console.log(req.body) 
    Blog.create({content: req.body.data}, function(err, item){ 
     if(err) return console.log(err) 
     res.json({serverSays: "Request received. Added item.", item: item}) 
    }) 
}) 

module.exports = router; 
+0

あなたのテーブルを見ることができますか?構造? – Beginner

答えて

0

この

に保存するためにあなたのコードを変更してみてください
Blog.create({content: req.body.data}) 
    .then(function(item){ 
     res.json({serverSays: "Request received. Added item.", item: item}) 
    }) 
    .catch(function(err) { 
     return console.log(err) 
    }) 
関連する問題