我正在构建一个node.js应用程序,它将使用knox将文件上传到我的S3存储桶.我可以按预期与S3进行交互,但我想让我的控制器接收配置,这样我就可以使用配置值动态构建我的客户端.
我的问题是如何在没有粗心的情况下将调用堆栈中的配置参数调到我的控制器?@H_404_3@
免责声明:我对Node.js比较陌生,所以可能只是我对出口差异的了解不足.和module.exports.*@H_404_3@
app.js@H_404_3@
... config = require('./config/config')['env']; require('./config/router')(app,config); ...
router.js@H_404_3@
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@H_404_3@
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 } ...
解决方法
尝试做这样的事……
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);
然后在你的控制器动作……@H_404_3@
exports.upload = function(req,res) { //Your config should be here... console.log(req.config); }