Sunday, 9 April 2017

How do you use different route.js module exports for the same app.use('/', root prefix?

I have been writing all of my routes in my app.js file via app.use('/etc', function) but the file has gotten 1000+ lines long so I need to modularize it.

I've started by creating a routes folder in my file structure, which has an index.js file in it which will handle exporting different route structures and automation of route exporting, using, requiring.

routes
-CMS
--admin
---all.js //Contains all the admin related routing AKA /login /register /logout /dashboard
--index
---all.js //Contains the website page routing such as '/' /home /shop /contactus
-index.js
models
views
app.js

So my routes/index.js file looks something like this

// routes/index.js

var express = require('express');
var router = express.Router(),
fs = require('fs'),
path = require('path'),
glob = require('glob');

// This was meant to be for automatically getting all routes and using them in app.js via app.use('/', allroutes) where allroutes = require('routes')
// glob.sync('./routes/CMS/pages/**/*.js').forEach(function(file) {
//  var filename = file.replace('.js','');
//  module.exports[filename] = require(file);
// });


module.exports.index = require('./CMS/pages/index/all.js');
module.exports.CMS = require('./CMS/pages/admin/all.js');

and then in the all.js file we've got

// routes/CMS/pages/admin/all.js

var express = require('express');
var router = express.Router(),
path = require('path'),
fs = require('fs');

router.get('/login', function(req, res) {
    if (req.session && req.session.user) {
        User.findOne({username: req.session.user.username}, function(err, user) {
            if (!user) {
                req.session.destroy();
                res.render('snippets/admin/login');
            } else {
                console.log("router.get /login req.session.user");
                console.log(req.session.user);
                res.locals.user = req.session.user;
                res.redirect('/Dashboard');
            }
        })
    } else {
        res.render('snippets/admin/login')
    }
});

module.exports = router;

And then in my app.js we're looking at importing all the routes to be used at the root domain '/' via

// app.js
const routes = require('./routes')
app.use('/', routes.index && routes.CMS); //But I'm not sure if this is valid?

The problem I'm running into is that I was defining some middleware to run on all routes via

ReferenceError: reqLog is not defined
1|myleisur |     at Object.<anonymous> (/home/ggg/Dropbox/host-root/var/www/myleisure.com.au/routes/CMS/pages/admin/all.js:54:26)

// app.js
app.use(function(req, res, next) {
  // some middleware
});

and using a function to define some require login pages like so

// app.js
function reqLog(req, res, next) {
  if(!req.session.user) {
    res.redirect('/Login')
  } else {
    next();
  }
});

but I'm getting an error when trying to use these routes which says reqLog isn't defined. I understand why, the routes files aren't getting the middleware passed to them or cannot access the middleware. So how would I go about having acccess to that middleware in those route files?

I've tried creating a router variable in app.js

// app.js
router = express.Router();
router.use(mymiddleware);

but that doesn't work.

And I've also tried passing the reqLog function into the routes require via

// app.js
routes = require('./routes');

// remember how I'm exporting each type of routing group as a property on the module.exports.etc

routes.admin.use(mymiddleware);
//and then
app.use('/', routes.admin);

But really all the routes need access to the middleware which verifies the user data in the cookie so is there a way of passing middleware to all required route files?

Sorry for the long post.

Thanks for any help.



via lopu

No comments:

Post a Comment