我正在构建一个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 } ...
解决方法
尝试做这样的事……
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); }
PS.我现在无法尝试,但我解决了类似的问题.