[英]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.