简体   繁体   English

无法将参数传递给Node.js中的导出方法

[英]Unable to pass parameter to export method in Node.js

Here is the sample.js : 这是sample.js:

module.exports = (function (param) {
   // I'm expecting param to be available here
})();

Here is the app.js 这是app.js

var sampleMsg= require('./controller/sample')(param);
app.use('/sample', sampleMsg);

But the above code when run throws the following error: 但是上面的代码在运行时会引发以下错误:

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

The code 编码

(function (param) {
   // I'm expecting param to be available here
})()

is a self-invoking function which returns undefined . 是一个自调用函数,返回undefined You can't invoke an undefined value as it's not a function. 您不能调用undefined值,因为它不是函数。 Also, in the above code param is also undefined as the invocation operator ( () ) doesn't pass any parameters to the anonymous function. 另外,在上面的代码中, param也是undefined因为调用运算符( () )不会将任何参数传递给匿名函数。 In the following code param is "I'm the param" string: 在以下代码中, param"I'm the param"字符串:

(function (param) {
   // ...
})("I'm the param");

It not clear why you are using a self-invoking function here. 尚不清楚为什么在此使用自调用功能。 If you need to use a closure the syntax should be: 如果需要使用闭包,则语法应为:

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.

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