简体   繁体   中英

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

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?

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?

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. So conB.js is:

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

Then in 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. See: 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:

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);
}

file - conB.js

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

}

file - conA.js //here you want to use exported object from 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') 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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