Express.js - How do I use a route that's not under the current router

Viewed 30

app.js:

var app = express();
app.use('/my-page', require('./routes/my-page.js'));

my-page.js:

const router = require('express').Router();

router.get('/one', function (req, res, next) {
    return res.send('this is /my-page/one');
});

router.get('/my-other-page', function (req, res, next) {
    return res.send('this is /my-other-page');
});

How do I make it so my-other-page isn't under my-page, but is instead on the root? I do not want to change app.js because i still want most routes under that page, just one specific one that I want to not have /my-page.

I tried .. in the route but doesnt work. I tried making app from app.js global, but that didn't seem to work either.

1 Answers

Typically you have a routes.js that can import the other routes. (You don't need to, but I think it will better for your structure).

app.js

var app = express();
app.use('/', require('./routes/routes.js'));

routes.js

const router = require('express').Router();
router.use('/my-page', require('./my-page.js'));
router.use('/my-other-page', require('./my-other-page.js'));

Then you split my-page.js and my-other-page.js.

my-page.js

const router = require('express').Router();

// This is /my-page/one
router.get('/one', function (req, res, next) {
    return res.send('this is /my-page/one');
});

my-other-page.js

// This is /my-other-page/one
router.get('/one', function (req, res, next) {
    return res.send('this is /my-other-page/one');
});
Related