2016-09-14 30 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) 
    }) 
相關問題