[英]How do I export this named function through module.exports?
[英]Why do I get 'Next is not a function' when I try to export a Middleware function to module.exports object?
我在logger.js
模块中编写了一个中间件函数,然后将其导入到app.js
并使用
// ------ File : logger.js ------ // function log(req, res, next) { console.log('Logging details ... '); next(); } module.exports = log; // ------ File : app.js -------- // const logger = require('./logger'); app.use(logger);
上面的代码可以正常工作,我的日志功能也可以工作。 但是,如果我以以下方式导出此日志功能(将其添加到module.exports
对象), module.exports
收到错误消息
// ------ File : logger.js -------// function log(req, res, next) { console.log('Logging details ... '); next(); } module.exports.log = log; // ------ File : app.js -------- // const logger = require('./logger'); app.use(logger.log());
Logging details ... D:\\express-demo-worked\\logger.js:4 next(); ^ TypeError: next is not a function at Object.log (D:\\express-demo-worked\\logger.js:4:5) at Object.<anonymous> (D:\\express-demo-worked\\app.js:18:16) at Module._compile (internal/modules/cjs/loader.js:738:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10) at Module.load (internal/modules/cjs/loader.js:630:32) at tryModuleLoad (internal/modules/cjs/loader.js:570:12) at Function.Module._load (internal/modules/cjs/loader.js:562:3) at Function.Module.runMain (internal/modules/cjs/loader.js:801:12) at internal/main/run_main_module.js:21:11 [nodemon] app crashed - waiting for file changes before starting...
有人可以向我解释为什么这种行为会有所不同,以及如何纠正我在此处添加的第二个代码段吗?
app.use(logger.log());
这将立即调用logger.log,不传递任何参数。 不管logger.log返回什么,都将传递到app.use中。 由于您未传入任何参数,因此next是未定义的,从而导致该异常。
相反,请执行以下操作:
app.use(logger.log);
这会将logger.log传递到app.use中。 稍后,将调用logger.log,并传递正确的参数。
这里:
app.use(logger.log());
您正在调用 log
(不带任何参数),并将其返回值传递到app.use
。 由于log
期望并使用其参数,因此在next()
上将失败,因为next
参数的值是undefined
,因为您没有为其传递参数。
您可能只是想将函数传递给:
app.use(logger.log);
// No () ---------^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.