简体   繁体   English

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

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

I want to pass params to method declared in controller B, says it's conB.js and look like this 我想将参数传递给控制器​​B中声明的方法,说它是conB.js,看起来像这样

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

Then now I'm have conA.js, how can I pass arguments to it? 然后,现在我有了conA.js,如何将参数传递给它?

I know firstly I have to include it, 我知道首先我必须包括它,

var ConB = require('ConB');

but how to pass param to verify method like ConB.verify('param') so that I can get it in ConA.js? 但是如何传递参数来验证ConB.verify('param')之类的方法,以便可以在ConA.js中获得它?

Not sure I undestand what you are trying to do but if you want to call verify with a parameter you have to define as a function accepting the parameter. 不确定我是否理解您要执行的操作,但是如果要使用参数调用verify,则必须将其定义为接受该参数的函数。 So conB.js is: 所以conB.js是:

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

Then in conA.js: 然后在conA.js中:

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

Update after comment... 评论后更新...

You can also write the different controllers as express middleware and pass parameters along using res.locals. 您还可以将不同的控制器编写为快速中间件,并使用res.locals传递参数。 See: http://expressjs.com/en/guide/using-middleware.html 请参阅: http : //expressjs.com/en/guide/using-middleware.html

In this case you need a route in you app that calls the middlewares in sequence: 在这种情况下,您需要在应用程序中按顺序调用中间件的路由:

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

Then consB.js is something like: 然后,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 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);
}

file - conB.js 文件-conB.js

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

}

file - conA.js //here you want to use exported object from conB.js file-conA.js //这里要使用从conB.js导出的对象

So what you can do this if both the files are in same folder otherwise you have to use relative paths. 因此,如果两个文件都在同一文件夹中,您可以执行此操作,否则必须使用相对路径。

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

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

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