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.