AJAX发布数据几乎保存到数据库?

时间:2014-05-05 21:35:57

标签: javascript jquery ajax node.js express

测试模块,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

2 个答案:

答案 0 :(得分:0)

替换data: AjaxPostData,

data : JSON.stringify(AjaxPostData), 我不相信数据正确传递,这就是它在[Object object]发送的原因

答案 1 :(得分:0)

原来,ajax点击事件需要e.preventDefault();return false;

$('#SubmitBtn').click(function(e) {

    e.preventDefault();

    // do something
});

$('#SubmitBtn').click(function() {

    //do something

    return false;
});

在这种情况下都可以工作。虽然这里有一篇关于差异的好文章:event.preventDefault() vs. return false