【问题标题】:How to specify a collection name in $http call?如何在 $http 调用中指定集合名称?
【发布时间】:2015-12-20 21:26:56
【问题描述】:

我的 MongoDB 数据库中有多个集合。我有一个 angularJS 应用程序,它必须根据上下文发布到不同的集合。

如何在 $http 调用中指定集合的​​名称并拥有通用的 REST API?

$http函数:

$http({
    method:"post",
    url:"http://localhost:8080/insertIntoTable",
    headers:"",
    data:"data"
}).success(function(data, status, headers, config) {
    $window.alert('Rest API successful');
}).error(function(data, status, headers, config) {
    $window.alert('Unsuccessful');
});

后端的post方法:

app.post('/insertIntoTable',function(req,res){
    //Establish Connection between client and server
    MongoClient.connect(url,function(err,db){
       //Connection Status Display
       if(err)
           console.log('Error while establishing connection with MongoDB',err);
       else
           console.log('Successfully established connection with MongoDB');
       var collection = db.collection(collectionName);
       collection.insert({ "name": "abc", "email": "xyz" });
       db.close();
       console.log('Connection with MongoDB is terminated');
   })
});

在上面的代码中,我想在 $http 调用中传递变量的值:collectionName。我该怎么做?

【问题讨论】:

    标签: angularjs node.js mongodb mean-stack mongodb-rest


    【解决方案1】:

    Node.js

    这种方法从request 查询字符串中读取一个属性并将其用作表名。为防止出现安全问题,还需要对 tableName 进行验证。

    // list of valid table names to avoid security issues.
    var validTables = ['users', 'customers', 'orders'];
    app.post('/insertIntoTable/:tableName', function(req, res) {
       var tableName= req.params.tableName;
       // verify if the table name is a valid table name.
       if (validTables.indexOf(tableName) === -1) {
            res.status(404).send('Not found');       // HTTP status 404: NotFound
            return;               
       }
       // use tableName as collection name. 
    }
    

    在 AngularJs 中

    在客户端,将表名作为常规路径发送,即如下例所示发出请求:

    $http({
        method:"post",
        url:"http://localhost:8080/insertIntoTable/users", // note "users"
        data:"data"
    }).success(function(data, status, headers, config) {
        // process success
    }).error(function(data, status, headers, config) {
        // process error
    });
    

    【讨论】:

    • 虽然这是对发帖者提出的问题的有效且正确的答案,但应注意,从客户端硬编码和传递关键数据库标识符(如集合名称、表名称、数据库名称等)不是从安全的角度来看,良好的编程实践。而是在服务器端进行交叉引用。
    • @user3658423 :我是新手,没有意识到安全问题。您能否指导我获取有关服务器端交叉引用的有用资源?谢谢
    • @DishaMathad 我编辑了答案以包括对表名的验证。
    • 你也可以阅读这篇有用的文章programmers.stackexchange.com/questions/46716/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2016-09-08
    • 2021-07-29
    相关资源
    最近更新 更多