Javascript ajax请求从nodejs中的表单发布未定义的数据

Javascript ajax请求从nodejs中的表单发布未定义的数据,javascript,jquery,node.js,ajax,Javascript,Jquery,Node.js,Ajax,我试图制作一个评论表单,在blog模式的数组中添加一个评论 但是当我使用ajax时,它会在我有控制台日志的地方给出未定义的消息,当我使用简单的post请求时,它工作得很好。 我正在使用mongoose、nodejs、express、jQueryAjax 我的剧本如下 var frm = $('#commentForm'); frm.submit(function (e) { e.preventDefault(); console.log('clicked'); $.aj

我试图制作一个评论表单,在blog模式的数组中添加一个评论 但是当我使用ajax时,它会在我有控制台日志的地方给出未定义的消息,当我使用简单的post请求时,它工作得很好。 我正在使用mongoose、nodejs、express、jQueryAjax 我的剧本如下

var frm = $('#commentForm');

frm.submit(function (e) {
    e.preventDefault();
    console.log('clicked');
    $.ajax({
        type: 'POST',
        url: "/blog/addComment",
        contentType: "application/json; charset=utf-8",
        dataType: 'json'
        })
        .done(function(data) {
            addNewComment(data);
        })
        .fail(function() {
            console.log("Ajax failed to fetch data");
        });
});

function addNewComment(data){
    console.log(data);
}
//add comments
router.post('/addComment',function(req,res,next){
    console.log(req.body.comment+" "+ req.body.userId+" "+req.body.postId);
    var newComment = {
        'text': req.body.comment,
        'author': req.body.userId
    }
    Post.addComment(req.body.postId, newComment, function(err,comment){
        if(err) throw err;
        console.log(comment);
        res.send(comment);
    });
});
我的路线如下

var frm = $('#commentForm');

frm.submit(function (e) {
    e.preventDefault();
    console.log('clicked');
    $.ajax({
        type: 'POST',
        url: "/blog/addComment",
        contentType: "application/json; charset=utf-8",
        dataType: 'json'
        })
        .done(function(data) {
            addNewComment(data);
        })
        .fail(function() {
            console.log("Ajax failed to fetch data");
        });
});

function addNewComment(data){
    console.log(data);
}
//add comments
router.post('/addComment',function(req,res,next){
    console.log(req.body.comment+" "+ req.body.userId+" "+req.body.postId);
    var newComment = {
        'text': req.body.comment,
        'author': req.body.userId
    }
    Post.addComment(req.body.postId, newComment, function(err,comment){
        if(err) throw err;
        console.log(comment);
        res.send(comment);
    });
});
我的猫鼬模式是

//add comments
module.exports.addComment = function( postId, newComment, callback){
    var query = { '_id': postId};
    console.log('postid: '+postId+"  newcomment: "+newComment.text+ " "+newComment.author);
    Post.findOneAndUpdate( query, { $push:{'comments': newComment} }, {new:true} , callback);
}

这是因为数据不是在ajax调用中定义的, 如果frm是ACTALU形式或用途,则使用以下内容 使用数据:表单名称。序列化()


从外观上看,$.ajax没有在请求中发送任何实际数据。选项中缺少
数据
参数。可能
data:frm.serialize()
就是您想要的