如何在nodejs中将值从路由器传递到控制器

时间:2018-04-23 06:40:56

标签: node.js express routing

我想将app.locals值传递给控制器​​函数。我如何在控制器内传递变量。

var enroll_controller=require('../enrollController');
    router.post('/enroll',function(req,res){
        var contractAddress=req.app.locals.contractAddress;
        enroll_controller.newUser
    });

我想将contractAddress传递给enroll_controller? 任何人

3 个答案:

答案 0 :(得分:0)

将其作为中间件传递:

router.post('/enroll',enroll_controller.newUser);

在您的控制器功能中,您可以直接使用它:

exports.newUser=function(req,res){
var contractAddress=req.app.locals.contractAddress
}

答案 1 :(得分:0)

如果希望每个路由都可以使用,那么您可以编写全局中间件并在该中间件中设置这些值。

// in your app.js file or main file which is wiring up application
app.use(function(req,res,next){
 req.app.locals.contractAddress = "Set address here."
 next();
});

var enroll_controller=require('../enrollController');
router.post('/enroll',enroll_controller.newUser);

或者您可以导出将上述中间件仅运行到一个路由并设置该特定路由的地址。

    var enroll_controller=require('../enrollController');
    router.post('/enroll',
     function(req,res, next){
        // middleware running to one route only. 
        req.app.locals.contractAddress = 'set address here';        
        next();
     },
     enroll_controller.newUser
    );

您还可以从文件中导出此中间件,然后重复使用它,而不是每次都定义为匿名函数。

答案 2 :(得分:0)

如果您不想使用中间件,也可以尝试使用。

var enroll_controller=require('../enrollController');
router.post('/enroll',function(req,res){
    enroll_controller.newUser(req,res);
});

enrollCntroller.js

exports.newuser=function(req,res){
  var contractAddress=req.app.locals.contractAddress
}