Home > Blockchain >  Cannot export more than one function using module.export
Cannot export more than one function using module.export

Time:01-10

I am getting the following error when I try to start my Node/Express app. The issue appears to be caused by using module.exports to export multiple functions from the same file. That is, the app starts fine and the route middleware works only if I export a single function.

Error: Route.get() requires a callback function but got a [object Object]

Here is the route

router.get('/check', MW.isAuth, function (req, res) { // including MW.otherMiddleware here causes error
    res.send({ messsage: 'Auth passed' })
})

And this is the contents of the middleware file.

function isAuth(req, res, next) {
    const authorized = false
    if (authorized) {
        // User is authorized, call next
        console.log('Auth passed...')
        next()
    } else {
        // User is not authorized
        res.status(401).send('You are not authorized to access this content')
    }
}

function otherMiddleware(req, res, next) {
    console.log('More MW operations..')
    next()
}


module.exports = { isAuth, otherMiddleware } 

Changing to module.exports = isAuth or if I leave the otherMiddleware out of the route doesn't cause the error.

If anyone can tell me where I am going wrong here I'd much appreciate it.

CodePudding user response:

You don't show us the importing code so the mistake is that the import code isn't matching the export code and thus you're ending up with an object for your middleware instead of the middleware function.

If you're exporting like this:

module.exports = { isAuth, otherMiddleware };

Then, this is how you would import:

const MW = require("./middleware.js");

router.get('/check', MW.isAuth, MW.otherMiddleware, function (req, res) {
     res.send({ messsage: 'Auth passed' })
});

Or, you could use destructuring assignment like this:

const { isAuth, otherMiddlware } = require("./middleware.js");

router.get('/check', isAuth, otherMiddleware, function (req, res) {
     res.send({ messsage: 'Auth passed' })
});

The specific error you were getting appears like you were doing something like this:

const isAuth = require("./middleware.js");

which would get you the module.exports object, not your middleware and thus it would not be a function and you'd get this error:

Error: Route.get() requires a callback function but got a [object Object]

That specific error means you're passing an object, not a function to .get(). So something in your exports isn't matching up with the way you're importing.

  • Related