Multiple module.exports - node.js

I have this code here
var router = require('./Router/index')(app, passport);
Im passing app and passport to my index.js file
module.exports = function (app,passport) {
// App's API
app.use('/api', require('./Routes/AppRoute'));
// Website
app.use('/', require('./Routes/Website'));
app.use('/keys', require('./Routes/KeysRoute'));
app.use('/users', require('./Routes/UsersRoute'));
};
Im going to use passport in my website route file
var express = require('express');
var router = express.Router();
var Users = require('../../Class/Users');
router.get('/CreateUser', function (req, res) {
Users.getUsers(function(result){
res.render('NewUser');
});
});
module.exports = router;
How can i pass the passport object over to be used in my website route file?

You can use the pattern further of exporting a function. Though, instead of exporting the router, the function can return it.
var express = require('express');
var Users = require('../../Class/Users');
module.exports = function (passport) {
var router = express.Router();
// ...
return router;
};
Then, invoking the exported function to pass along passport from index.js:
module.exports = function (app,passport) {
// App's API
app.use('/api', require('./Routes/AppRoute')(passport));
// ...

module.exports = function (app,passport) {
// App's API
app.use('/api', require('./Routes/AppRoute'));
// Website
app.use('/', require('./Routes/Website')(passport));
app.use('/keys', require('./Routes/KeysRoute'));
app.use('/users', require('./Routes/UsersRoute'));
};
You Website route file
var express = require('express');
var router = express.Router();
var Users = require('../../Class/Users');
module.exports = function (passport) {
router.get('/CreateUser', function (req, res) {
Users.getUsers(function(result){
res.render('NewUser');
});
});
}

Related

How can I separate route files?

I have a route file in my project and it is called from my app with these lines:
var index = require('./routes/index');
app.use('/', index);
But I need to separate the route file, and I'm trying to do this:
var index = require('./routes/index');
var user = require('./routes/user');
app.use('/', index);
app.use('/user', user);
In route user.js I put the service that I need to access from the client. But it's not working. I don't know what is wrong, I am a beginner in Node.js.
The request returns:
GET /user/find 304 4.203 ms - -
And user.js file is:
var router = express.Router();
router.get('/user/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
*This request works well on index.js
You put user router under /user route, and in your user router you defined app.get('/user/find'), so the actual path would be /user/user/find, you need to remove the user prefix in router
var router = express.Router();
router.get('/find',function(req, res){
Object.find(function(err, s){
if(err) res.send(err);
res.json(s);
});
});
module.exports = router;
A simple way to do this can be:
index.js
var express = require('express')
var app = express()
var route1 = require('./route1')
var route2 = require('./route2')
app.use('/', route1);
app.use('/hello', route2);
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
route1.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route1');
})
module.exports = router
route2.js
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Hello route2');
})
module.exports = router
Have you made sure to include a module.exports = router at the end of each of your route files?
Your route files should be set up thusly:
var router = require('express').Router();
router.get("/example", function (req, res) {
res.send("Hello");
});
module.exports = router;

Express Middleware Issue

On routes/index.js it works fine if I leave the module.exports = routes;
But If I change it to the following to allow multiple files then I get a middleware error:
module.exports = {
routes
};
var app = express();
const routes = require('./routes');
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use('/', routes);
app.get('/', (req, res) => {
res.send('Please visit: http://domain.com');
}, (err) => {
res.send(err);
});
//routes/index.js
const routes = require('./MainRoutes');
module.exports = routes;
//routes/Main Routes.js
const routes = require('express').Router();
routes.post('/main', (res, req) => {
//code here works
});
module.exports = routes;
The error is: Router.use() requires middleware function but got a ' + gettype(fn));
MainRoutes.js exports the express router object, which middleware will understand just fine if you do
module.exports = routes; // routes/index.js
However, when you do
module.exports = {
routes
};
You are now nesting that router object in another object, which middleware can't understand.
In your main server file you can do
const {routes} = require('./routes');
to get the router object properly.
Modify the routes/index.js as:
const routes = require('express').Router();
routes.use('/main', require('./MainRoutes'));
// Put other route paths here
// eg. routes.use('/other', require('./OtherRoutes'))
module.exports = routes;
Modify the Main Routes.js as:
const routes = require('express').Router();
routes.post('/', (res, req) => {
// route controller code here
});
module.exports = routes;
Hope this helps you.

NodeJS Express multiple route file through one route file

I am learning NodeJS. I have a nodeJS API project. I want to use version in routes so i created following folder structure.
application/
--app.js
--routes/
----V1/
------routes.js
------users.js
Here is my app.js file:
var v1 = require('./routes/v1/route');
app.use('/api/v1', v1.router);
And this is route.js file:
var express = require('express');
var router = express.Router();
router.get('/',function(req,res){
res.send("Welcome to Node JS V1");
});
var courses = require('./users').router;
-- How to include usres route here
module.exports.router = router;
users.js file:
var express = require('express');
var router = express.Router();
router.get('/',function(req,res){
res.send("Get all users.");
});
module.exports.router = router;
Now how i can call users from route.js file.
I'd do it a bit different than #Shaharyar
routes.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('Welcome to Node JS V1');
});
router.use('/users', require('./users').router);
module.exports.router = router;
users.js
var express = require('express');
var router = express.Router();
router.get('/',function(req, res){
res.send('Get all users.');
});
router.post('/', function(req, res) {
// Create user
res.send('Some response.');
});
module.exports.router = router;
To simplify it I'd drop the .router on module.exports and do.
router.use('/users', require('./users'));
Also the same for the route.js file, then in your server.js or wherever:
router.use('/api/v1', require('./routes'));
router.use('/api/v2', require('./routes2'));
You should create express instance once and pass it into all modules.
route.js file
//initialize
var express = require('express');
var router = express.Router();
router.get('/', function(req, res){
res.send("Welcome to Node JS V1");
});
//modules
require('./users')(router);
require('./sessions')(router); //added for explaination
require('./comments')(router); //added for explaination
//export
module.exports.router = router;
module file (any module users, comments etc)
//initialize
module.exports = function (router) {
router.get('/users', users);
}
//APIs
function users(req, res) {
res.send("Get all users.");
}

ERROR app.use() requires middleware functions: (so how to set router for app.use in express node.js)?

basically im just trying to seprate routes, models, and controller in node.js application.
i have following files to setup very very basic node.js application.
controller/cv.js
module.exports = {
get: function(req, res, next){
console.log("GET REQUESTS")
next();
}
}
routes/cv.js
var express = require('express');
var CvRouter = express.Router();
var CvController = require('../controller/cv')
CvRouter.get('/', function(req, res, next){
console.log("GET REQUESTS")
next();
})
module.export = CvRouter
app.js
const express = require('express');
const bodyParser= require('body-parser')
var path = require('path')
const app = express();
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
var router = express.Router();
require('./router')(app)
app.listen(3000, function() {
console.log('listening on 3000')
})
router.js
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use([CvRouter]);
};
Basicaly this last file router.js is generting error when i use app.use([CvRouter])
ERROR is: throw new TypeError('app.use() requires middleware functions');
how i can resolve it? i also know its returning object of router. and app.use expecting function in parameter. but how i can achieve my desired MVC pattern of node.js?
as said in comment - you have a typo.
The file routes/cv.js contains module.export instead of module.exports, that makes CvRouter undefined.
Kill the array literal
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use(CvRouter);
};

Is there a better way to use middleware in middleware?

For example I want to create some middleware that uses Passport but I don't want to have to require Passport in my app(s) that use this custom middleware. I believe I can do the following to achieve this. Is this proper? Is there a better way to do this?
someModule.js
var express = require('express'),
passport = require('passport');
exports.someMiddleware = function(app) {
app.use(passport.initialize());
app.use(passport.session());
return function(req, res, next) {
// Do something
next();
}
}
app.js
var express = require('express');
var someModule = require('./someModule');
app = express();
app.use(someModule.someMiddleware(app))
rather than......
someModule.js
var express = require('express'),
passport = require('passport');
exports.someMiddleware = function(app) {
return function(req, res, next) {
// Do something
next();
}
}
app.js
var express = require('express'),
passport = require('passport');
var someModule = require('./someModule');
app = express();
app.use(passport.initialize());
app.use(passport.session());
app.use(someModule.someMiddleware())
I recommend using embedded apps to keep code well organized and reusable. Keep routes in the embedded app as short as possible, so that the main app that is using them can set an appropriate base path.
module.js
var express = require('express');
var passport = require('passport');
var controller = module.exports = express();
controller.use(passport.initialize());
controller.use(passport.session());
// Login
controller.post('/', function (request, response, next) { /* ... */ });
// Logout
controller.del('/', function (request, response, next) { /* ... */ });
app.js
var app = express();
var controller = require('./controllers/module');
app.use('/authentication', controller);

Resources