【问题标题】:get the parmeter from ajax to node.js to mongoDB从 ajax 到 node.js 到 mongoDB 获取参数
【发布时间】:2014-04-18 04:23:35
【问题描述】:

当我尝试通过单击一个按钮进行一些测试时遇到这个问题,该按钮调用一个执行 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.");
            }
       });

    }
}

【问题讨论】:

  • 什么是服务器端应用程序框架?如果使用 express,则需要 bodyParser

标签: javascript jquery ajax node.js mongodb


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 2018-03-16
    • 2021-06-02
    • 2018-03-11
    • 1970-01-01
    • 2023-03-17
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多