【发布时间】:2014-06-22 08:04:25
【问题描述】:
测试模块,AJAX 正在浏览器的 console.log 中正确发布,并且 Node.js/express4 mongoose .save 方法正在正确保存到 MongoDB(使用 Postman - REST Client 进行测试)
由于某种原因,AJAX 发布数据尚未进入数据库,尽管它准确地记录了数据..
$(document).ready(function(){
$('#SubmitBtn').click(function() {
var message = $( "#message" ).val();
console.log(message); // logs as the "user's message"
var AjaxPostData = {'message' : message};
console.log(AjaxPostData); // logs as [object Object]
// make an ajax call
$.ajax({
dataType: 'json',
data: AjaxPostData,
type: 'post',
url:"http://localhost:4200/api/v1/stories",
success: foundAllSuccess,
error: foundAllFailure
});
console.log(AjaxPostData.message); // logs as the "user's message"
});
});
Express4 路由:
var router = express.Router(); // an instance of the express Router
var Story = require('./app/models/story'); // load the mongoose model
router.route('/stories')
// create a story (accessed at POST http://localhost:4200/api/v1/stories)
.post(function(req, res) {
var story = new Story(); // create a new instance of the Story model
story.message = req.body.message; // set the message, from the request
console.log(req.body.message); // logs with Postman, yet the ajax post
// save the story, and check for errors
story.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Story "' + story.message + '" Created' });
});
})
app.use( '/api/v1', router ); // all of the routes are prefixed
【问题讨论】:
-
您能否更具体地说明这里错误的性质?当您发布 AJAX 帖子时,您的
req.body.message的 console.log 是否包含适当的内容?我还建议使用new Story({message: req.body.message}).save(callback),因为它更干净一些。最后,我将删除您对AjaxPostData的定义中的引号,因为据我所知,它们不是必需的。 -
@Michael req.body.message 的控制台日志没有记录 ajax 帖子。感谢建议的格式。将测试一切
-
@Michael 将格式修改为您更简洁的建议。控制台正在使用 POSTMAN 测试记录 req.body.message,而不是 ajax。也删除了引号,仍然没有保存 ajax 数据。任何其他建议?
标签: javascript jquery ajax node.js express