将配置传递给控制器

时间:2013-01-28 22:15:10

标签: node.js express knox-amazon-s3-client

我正在构建一个node.js应用程序,它将使用knox将文件上传到我的S3存储桶。我可以按预期与S3交互,但我想让我的控制器接收配置,这样我就可以使用配置值动态构建我的客户端。

我的问题是如何在不粗心的情况下将调用堆栈中的配置参数调到我的控制器?

免责声明:我对Node.js比较陌生,所以可能只是我对导出之间的差异缺乏了解。和module.exports。*

以下是交互如何与我的代码配合使用的示例:

app.js

...
config = require('./config/config')['env'];
require('./config/router')(app, config);
...

router.js

module.exports = function(app, config) {
...
  var controller = require('../app/controllers/home'); //Is there a way for me to pass config here?
  app.post('/upload', controller.upload); //Or here?
...
}

home.js

var knox = require('knox');

var client = knox.createClient({ ... }); //I want to use config.key, config.secret, etc instead of hard-coded values
...
exports.upload = function(req, res) {
  //Use client
}
...

3 个答案:

答案 0 :(得分:8)

尝试做这样的事情......

var config = require('./config/config')['env'];

// The use function will be called before your 
//  action, because it is registered first.
app.use(function (req, res, next) {

  // Assign the config to the req object
  req.config = config;

  // Call the next function in the pipeline (your controller actions).
  return next();

});

// After app.use you register your controller action
app.post('/upload', controller.upload); 

然后在你的控制器动作......

exports.upload = function(req, res) {

  //Your config should be here...
  console.log(req.config);

}

聚苯乙烯。我现在无法尝试,但我解决了类似的问题。

答案 1 :(得分:1)

您可以将配置作为参数传递给控制器​​

控制器

// controller.js file
module.exports = function(req, res, config) {
  console.log('config parameter passed to controller', config);
  res.end('config passed')
}

应用

// index.js file with the express app
var controller = require('./controller');
var config = {
  key1: 'foo'
};
var express = require('express');
var app = express();
var port = 3000;
app.get('/', function(req, res){
  controller(req, res, config);
});
app.listen(port);

console.log('app listening on port', 3000);

演示

您可以查看github repo以获取完整示例

答案 2 :(得分:0)

如果你想从一条路线调用多个功能,可以采用其他方法,这样就可以了。

路线

var users = require('../controllers/users');
 app.route('/login').post(function(req, res){
   if(users.authenticate()){
     console.log('valid user');
     if(users.createUser())
     {
       console.log('user created');
     }
   }
});

控制器

exports.authenticate = function(req, res, next) {
   return true;
};
exports.createUser = function(req, res, next) {
   return true;
};
相关问题