这是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
答案 0 :(得分:0)
代码
(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);