[英]Why do I get 'Next is not a function' when I try to export a Middleware function to module.exports object?
I have a middleware function written inside my logger.js
module which I then import into app.js
and use 我在
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);
The above code works without any issue and my log functionality works. 上面的代码可以正常工作,我的日志功能也可以工作。 However, if I export this log function in the following way (add it to the
module.exports
object), I get an error 但是,如果我以以下方式导出此日志功能(将其添加到
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...
Can someone explain to me why this behaves differently and how to correct the second code snippet I added here? 有人可以向我解释为什么这种行为会有所不同,以及如何纠正我在此处添加的第二个代码段吗?
app.use(logger.log());
This will call logger.log immediately, passing in no arguments. 这将立即调用logger.log,不传递任何参数。 Whatever logger.log returns will then be passed into app.use.
不管logger.log返回什么,都将传递到app.use中。 Since you passed in no arguments, next is undefined, resulting in that exception.
由于您未传入任何参数,因此next是未定义的,从而导致该异常。
Instead, do: 相反,请执行以下操作:
app.use(logger.log);
This will pass logger.log into app.use. 这会将logger.log传递到app.use中。 At some point later, logger.log will be called, passing in the correct arguments.
稍后,将调用logger.log,并传递正确的参数。
Here: 这里:
app.use(logger.log());
you're calling log
, without any arguments, and passing its return value into app.use
. 您正在调用
log
(不带任何参数),并将其返回值传递到app.use
。 Since log
expects and uses its parameters, that will fail on next()
because the value of the next
parameter is undefined
, as you didn't pass an argument for it. 由于
log
期望并使用其参数,因此在next()
上将失败,因为next
参数的值是undefined
,因为您没有为其传递参数。
You may have meant just to pass the function in: 您可能只是想将函数传递给:
app.use(logger.log);
// No () ---------^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.