Monday, 8 May 2017

Separate Same Level Routes In Separate Route Files NodeJS Express

So instead of having my auth routes (register, login, etc) inside the main index.js route file, I'd like to have them separated like this:

routes
-- index.js
-- auth
  -- index.js
  -- login.js
  -- register.js

But I can't seem to get it work. I was thinking it would be like this:

// index.js
const express = require('express'),
      router = express.Router();

router.use('/', function(req, res) {
  // if not logged in, redirect login else redirect to dashboard
  res.send("hello world");
});

require('./auth/index.js');

module.exports = router;

Then...

// auth/index.js
const express = require('express'),
      router = express.Router();

router.use('/', require('./login.js'));
router.use('/', require('./register.js'));

module.exports = router;

Then...

// auth/login.js
const express = require('express'),
      router = express.Router();

router.use('/login', function(req, res) {
  console.log("Got here!");
  res.send("This is the login screen.")
});

module.exports = router;

But if I go to /login on my server, I just see hello world :(

Plenty of other posts but can't see how they organise code that exists on the same level since I'd like to have the end routes be

/
/login/
/register/

Not

/
/auth/login/
/auth/register/

Hope you understand where I am coming from.



via Jack Robson

No comments:

Post a Comment