0

我的 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。我该怎么做?

4

1 回答 1

1

节点.js

这种方法从请求查询字符串中读取一个属性并将其用作表名。为防止出现安全问题,还需要对 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
});
于 2015-12-20T05:45:32.870 回答