使用Javascript,NodeJS,MongoDB,Express
在我的应用程序中,用户可以输入输入字段,当他们单击提交按钮时,文本会附加到页面上。我能够成功地将文本发布到页面,但是当我刷新浏览器时,我的帖子没有显示出来。我想我需要在partials / test.ejs的脚本部分通过ajax做一个get请求,但我不确定如何执行它。
模型/ 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)
})
routes / 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 :(得分: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)
})