I’m building my node.js app which has the following structure:
- server.js
- controllers/user.js
server.js require the user.js controller with:
require('./controllers/user.js').route(app, mongoose);
the controller/user.js file is like:
function route(app, mongoose){
function route(app, mongoose){
// Create new User item
app.post('/user/create', function(req, res){
...
}
// Edit user
app.put('/user/:id/edit', function(req, res){
...
}
...
}
module.exports.route = route;
This is working fine.
I know want to had middleware in the Edit user function for instance so it looks like:
...
app.put('/user/:id/edit', loadUser, function(req, res){
...
If I define loadUser function right above this line it’s working fine. When I add all the middleware fonction in a file ‘./lib/middleware.js’ and when I try to load that file in user.js with:
require('../lib/middleware.js').create(); // Create is the exported function
this does not work and I have the error message saying that loadUser is an unknow function.
Any idea ?
** UPDATE **
I have updated the files such that, in server.js (main file) I have:
...
var middleware = require('./lib/middleware.js');
...
require('./controllers/user.js').route(app, mongoose, middleware);
...
In middleware.js, I then have:
function create() {
function loadUser(req, res, next) {
// You would fetch your user from the db
var user = users[req.params.id];
if (user) {
req.user = user;
next();
} else {
next(new Error('Failed to load user ' + req.params.id));
}
}
return module;
}
In controllers/user.js I have
function route(app, mongoose, middleware){
...
// Modify an user
app.put('/user/edit', middleware.loadUser, function(req, res){
...
}
...
}
When I run the app (node server.js) I then have the following error:
Error: PUT route /user/edit requires a callback
I am not sure to return the correct thing within middleware.js, not really familiar with module stuff yet. I also tried the “module.exports.create = create;” but same thing.
UPDATE WITH ANOTHER TRY
what if I create a module for the function ? In ./lib/middleware.js I would have:
(function(){
var middleware = {};
middleware.loadUser = function () {
console.log("loadUser");
}
return middleware;
}());
And in server, I call it:
var middleware = require('./lib/middleware.js');
middleware.loadUser;
It seems to me that should work but it does not…
“global” scope in a file is actually module scope. Just by creating a function in a different file it does become in scope in your original file.
What you want to do instead is
You will find that global variables actually write to
modulein their scope.Then your
function loadUser() { ... }should exist in themoduleproperty.If you return
modulefrom your create function your returning global scope.[Edit]
You either need to add
module.loadUser = loadUseror defineloadUserin module scope. I.e. outside thecreatefunction.[Further Edit]:
A standard setup would be something like: