Separate Same Level Routes In Separate Route Files NodeJS Express

275
May 09, 2017, at 09:56 AM

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.

Answer 1

LESSON LEARNED:

Need to use app.route (or router.route in this case) to actually create a single end route.

app.use can be used to assign a function, or set of functions (group of routes in this case) to a path.

// index.js
const express = require('express'),
      router = express.Router();
router.route("/")
  .get(function(req, res) {
    // if not logged in, redirect login else redirect to dashboard
    res.send("Hello World");
  })
router.use('/', require('./auth/index.js'));
module.exports = router;

AND...

// auth/login.js
const express = require('express'),
      router = express.Router();
router.route("/login")
  .get(function(req, res) {
    res.send("This is the login screen.")
  });
module.exports = router;
READ ALSO
Dynamic URL doesn't work properly angularjs

Dynamic URL doesn't work properly angularjs

I'm creating an app in angularJS and express but I'm a beginnerWhen I try to use dynamic url in the angular state, it doesn't work properly

257
How to repeat SQL insertion until successful with pg-promise?

How to repeat SQL insertion until successful with pg-promise?

In my program I insert some data into a table and get back it's id and I need to ensure I enter that id into another table with a unique randomly generated stringBut, in case the insertion fails for attempting to insert an already-existing random string,...

267
Dynamic redirect url through oAuth2.0

Dynamic redirect url through oAuth2.0

Hi I am making authentication using oAuth20 protocol in Node

270