简体   繁体   中英

“Error: Route.get() requires a callback function but got a [object Undefined]” when doing multiple exporting

I am trying to export the middleware function so that other classes can call it.

I did some google search but did not work for my case.

Here is the code

auth.js

isLoggedIn = (req, res, next) => {
  next();
}

module.exports.isLoggedIn = isLoggedIn;

module.exports = app => {
};

profile.js

const isLoggedIn = require('./auth').isLoggedIn;
let profile = [];
getAllProfile = (req, res) => {
    res.send(profile);
}

module.exports = (app) => {
    app.get('/all-profile',isLoggedIn, getAllProfile);

}

index.js

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());

const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
  const addr = server.address();
  console.log(`Server listening at ${port}`);
});


let auth = require("./src/auth");
auth(app);

let profile = require("./src/profile");
profile(app);

The error message is

\node_modules\express\lib\router\route.js:202
        throw new Error(msg);
        ^

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

What am I doing wrong here?

You are overwriting your module.exports with the second line here:

module.exports.isLoggedIn = isLoggedIn;

module.exports = app => {
};

So .isLoggedIn is no longer a property of the new exports object you assigned. You could flip the order:

module.exports = app => {
};

module.exports.isLoggedIn = isLoggedIn;

That way, you define a new module.exports object first (which happens to be a function object) and then add a property to the new object.

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