Avoid "require" repeating in Router files - node.js

This is a part of Main Server File in Nodejs
var express = require('express');
var request = require('request');
var app = express();
//Module for User Login , Logout, Session
var objUserModule = require('./node_scripts/UserModule');
app.use('/', objUserModule);
and in UserModule
var express = require('express');
var request = require('request');
var router = express.Router();
//LOGOUT USER
router.get('/LogOut', function(req, res) {});
Is there any way to avoid the require statements in beginning of all router files (avoid including those modules individually in each routers)
i m new to Nodejs and so i believe there is a better way to do this ...

You could pass in Router to the module. That way you don't have to require it again.
Main
var express = require('express');
var request = require('request');
var app = express();
//Module for User Login , Logout, Session
var objUserModule = require('./node_scripts/UserModule')(express.Router());
app.use('/', objUserModule);
UserModule
module.exports = function(router) {
//LOGOUT USER
router.get('/LogOut', function(req, res) {});
return router;
};

Related

Why cannot return params from url nodejs

Here my server code
var express = require("express");
var isAuthen = require('./middleware/authorize')
var router = express.Router();
var app = express();
var order_process = require('./routes/order-process');
app.use('/order',isAuthen, order_process);
and here order_process code
var express = require('express');
var bodyParser = require('body-parser');
const bcrypt = require("bcrypt");
var router = express.Router();
var db = require('../models/database');
router.get('/', urlencodedParser, function (req, res) {
try {
console.log(req.params);
}catch(err){
console.log(err);
}
module.exports = router;
http://localhost:3000/order/2
as i know that url should return number 2 ??
i dont know why it cannot return ?
should return correct params from url
Here's an example of how to get the params from a route:
const express = require('express');
const router = express.Router();
const app = express();
app.use('/order', router);
router.get('/:page', (req, res) => {
res.send(`You are viewing page ${req.params.page}`);
});
const server = app.listen(8000);
Then go to http://localhost:8000/order/2 and you should see it say:
You are viewing page 2

How to separate routes from app file in express framework

For example :
server.js file
var express = require('express'),
app = express(),
port = 3000,
routes = require('./app/routes/apiRoutes');
routes(app);
app.listen(port);
routes.js file
'use strict';
module.exports = function( app ) {
var api= require('../controllers/apiController');
app.route('/get').get(api.get);
};
apiController.js file
'use strict';
exports.get = function(req, res) {
// console.log( req.app ); // access it but it didn't work ?
// here want to access app to set cookie and changed cookie ?
};
if there is another way please help me thanks :)
If I correct understand your question, with routes you can do something like this:
In routes.js file:
var router = require('express').Router()
router.get('/home', function(req, res, next) {
res.render('index')
})
module.exports = router
In server.js file:
var mainRoutes = require('./routes.js')
app.use(mainRoutes)
Best way (in my opinion) to use controllers from another file it's use exports.functionName notation:
In someController.js file:
exports.homePage = function(req, res) {
res.render('index')
}
So, your router will looks like this:
var router = require('express').Router()
var someController = require('./someController.js')
router.get('/home', someController.homePage)
module.exports = router
Do different way, use route in app.use
app.js:
const
express = require('express'),
app = express(),
port = 3000,
routes = require('./app/routes/apiRoutes');
app.use(routes);
app.listen(port);
apiRoutes.js:
const
router = require('express').Router(),
apiController = require('../controllers/apiController');
router.get(
'/get',
apiController.get);
module.exports = router;
Check this example: app.js , some route file

Nodejs Express: Routes in separate files

I write my app.js including all the routes in the main file and everything was working well. After my goal was to make the project more clear by moving the routes in a different files but it is not working.
I'm passing an object instead of a middleware function and I don't know how to fix it in the right way.
So this is my app.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var myRoutes = require('./app/routes/myRoutes.js');
...
//parser for getting info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//for log requests to console
app.use(morgan('dev'));
app.use('/myRoutes', myRoutes);
app.get('/',function(req,res){
res.end('Welcome Page!');
});
//Server Start
app.listen(port);
console.log('server start at port ' + port);
And the app/routes/myRoutes.js contains the following code:
var express = require('express');
...
var myRoutes = express.Router();
myRoutes.get('/users',function(req,res){
...
});
myRoutes.post('/setup',function(req,res){
...
});
myRoutes.post('/remove', function(req,res){
...
});
module.export = myRoutes;
I also tried this:
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
But again it seems not passing a middleware function.
My second option code
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
is working fine! I just write it in a wrong way
module.export = myRoutes;
isntead of
module.exports = myRoutes;
Hi this is more of additional tips on the question. You main js file would definately need to load a lot of routes and i found importing all of them is a lot of work. Rather use require-dir module to load all the routes like
const loader = require('require-dir');
var app = express();
var routes = loader('./routes');
for (route in routes){
app.use("/"+route,routes[route]);
}
needless to say define all routes inside routes folder and export Router module in each one of them like
var router = express.Router();
router.get(....);
module.exports = router;

Using Express Router in routes.js

I am currently using routes in app.js as below:
// Router configuration
var router = express.Router();
router.route('/user')
.get(userController.getUser)
.post(userController.postUser);
app.use('/api', router);
Is it possible to put Express router routes in another file like routes.js and call from app.js? I tried with app.get in routes.js and it is working. But it is annoying to add /api for prefix in all routes as below.
module.exports = function(app){
app.get('/user', userController.getUser);
};
Or, is there anyway to use namespace in app.get too? Thank you
Why not just do what you're doing, but in your route file?
var express = require('express');
var router = express.Router();
router.route('/user')
.get(userController.getUser)
.post(userController.postUser);
module.exports = function(app) {
app.use('/api', router);
};
Then you'd have in your app.js file
require('./routes.js')(app);
Routers support namespaces too, so you could even do
app.use('/', require('./routes.js'));
And in your routes file (this can be split across files for modularity)
var express = require('express');
var mainRouter = express.Router();
var userRouter = express.Router();
userRouter.route('/user')
.get(userController.getUser)
.post(userController.postUser);
mainRouter.use('/api', userRouter);
module.exports = mainRouter;
You don't need to declare your routes in app.js, in fact, it's better to have each route in its own file, so you can write a routes/my_route.js file as:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Then in app.js:
var express = require("express");
var myRoute = require("./routes/my_route");
var app = express();
app.use("/my-route", myRoute);

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