[英]Unable to pass parameter to export method in Node.js
这是sample.js:
module.exports = (function (param) {
// I'm expecting param to be available here
})();
这是app.js
var sampleMsg= require('./controller/sample')(param);
app.use('/sample', sampleMsg);
但是上面的代码在运行时会引发以下错误:
D:\Working\GUI\Server\node_modules\express\lib\router\index.js:140
var search = 1 + req.url.indexOf('?');
^
TypeError: Cannot read property 'indexOf' of undefined
at Function.handle (D:\Working\GUI\Server\node_modules\express\lib
\router\index.js:140:27)
at router (D:\Working\GUI\Server\node_modules\express\lib\router\i
ndex.js:46:12)
at Object.<anonymous> (D:\Working\GUI\Server\app.js:267:54)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:504:3
编码
(function (param) {
// I'm expecting param to be available here
})()
是一个自调用函数,返回undefined
。 您不能调用undefined
值,因为它不是函数。 另外,在上面的代码中, param
也是undefined
因为调用运算符( ()
)不会将任何参数传递给匿名函数。 在以下代码中, param
是"I'm the param"
字符串:
(function (param) {
// ...
})("I'm the param");
尚不清楚为什么在此使用自调用功能。 如果需要使用闭包,则语法应为:
module.exports = function(param) {
return function(req, res, next) {
// ...
}
}
// ...
var routeHandler = require('./controller/sample')(param);
app.use('/sample', routeHandler);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.