简体   繁体   中英

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

 // ------ 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

 // ------ 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. Whatever logger.log returns will then be passed into app.use. Since you passed in no arguments, next is undefined, resulting in that exception.

Instead, do:

app.use(logger.log);

This will pass logger.log into app.use. At some point later, logger.log will be called, passing in the correct arguments.

Here:

app.use(logger.log());

you're calling log , without any arguments, and passing its return value into 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.

You may have meant just to pass the function in:

app.use(logger.log);
// No () ---------^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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