繁体   English   中英

将参数传递给另一个控制器公开的方法

[英]passing param to a method exposed from another controller

我想将参数传递给控制器​​B中声明的方法,说它是conB.js,看起来像这样

module.exports.verify = function(req,res,next){
// how to get it here?
}

然后,现在我有了conA.js,如何将参数传递给它?

我知道首先我必须包括它,

var ConB = require('ConB');

但是如何传递参数来验证ConB.verify('param')之类的方法,以便可以在ConA.js中获得它?

不确定我是否理解您要执行的操作,但是如果要使用参数调用verify,则必须将其定义为接受该参数的函数。 所以conB.js是:

module.exports.verify = function(param){
   // do something with param
   return something;
}

然后在conA.js中:

var conB = require('./conB.js');
var result = conB.verify(your_param);

评论后更新...

您还可以将不同的控制器编写为快速中间件,并使用res.locals传递参数。 请参阅: http : //expressjs.com/en/guide/using-middleware.html

在这种情况下,您需要在应用程序中按顺序调用中间件的路由:

app.use("/testUrl", consB.verify, cansA.doSomething);

然后,consB.js类似于:

module.exports.verify = function(req, res, next){
   // do something with param and store something in res.locals
   res.locals.user = "foo";
   // then remember to call next
   next();
}

ConsA.js

module.exports.doSomething = function(req, res, next) {
    // use locals modified by previous middleware
    res.end("The user of the request is: "+res.locals.user);
}

文件-conB.js

module.exports.verify = function(req,res,next){

}

file-conA.js //这里要使用从conB.js导出的对象

因此,如果两个文件都在同一文件夹中,您可以执行此操作,否则必须使用相对路径。

 var conB = require('./conB.js') 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM