获取从ajax到node.js再到mongoDB的parmeter

get the parmeter from ajax to node.js to mongoDB

本文关键字:再到 mongoDB parmeter js node ajax 获取      更新时间:2023-09-26

当我试图通过点击一个按钮来进行测试时,我遇到了这个问题,该按钮调用了一个执行ajax调用的JavaScript函数,并将一个参数传递给我的node.js服务器(express),后者将其保存到我的mongoDB中。

问题是,我一直看到DB中的值为null,经过研究,我发现问题是如何获得参数"name"并在node.js侧上读取它

我尝试了req.body.namereq.query.name,但什么都没有。。

希望你能帮助我,可能是我的代码或语法问题,请等待您的帮助

java脚本代码:

function savePre()
{
    var parameters = { name: 'test' };
    $.ajax({
        url: '/savePre',
        type: 'POST',
        data: JSON.stringify(parameters),
        success: function () {},
        dataType: 'json'
    });
}

node.js代码(在index.js代码中):

exports.savePre = function(db) {
    return function(req, res) {
        // Get our form values. These rely on the "name" attributes
        var json = req.query.name;
        // Set our collection
        var collection = db.get('PresentationCollection');
        // Submit to the DB
        collection.insert({
            "JsonToSave": json
        }, function (err, doc) {
            if (err) {
                // If it failed, return error
                res.send("There was a problem adding the information to the database.");
            }
       });
    }
}

您的客户端代码可以在没有JSON.stringify:的情况下得到改进

$.ajax({
    url: '/savePre',
    type: 'POST',
    data: parameters,
    success: function () {}
});