Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js express nested routes

I am new to Node.js and Express and have tried to go through some of the tutorials. I am able to get basic routing working one level deep (e.g., http://localhost/help), but I'm having trouble getting it to work two levels deep (e.g., http://localhost/help/test).

Here are the relevant lines in app.js:

var help = require('./routes/help');

// also tried this
//var help_test = require('./routes/help/test');

var app = express();
app.use('/help', help);
app.use('/help/test', help.test);

// also tried this
//app.use('/help/test', test);
//app.use('/help/test', help_test);

Under the routes directory I have two files: index.js and test.js.

The index.js consists of:

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

router.get('/', function(req, res) {
  res.send('help');
});

module.exports = router;

The test.js file consists of:

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


router.get('/test', function(req, res) {
  res.send('help test!');
});

module.exports = router;

Right now I can't start the server due to the configuration in app.js, but any changes I make so that I can start it results in a 404 error when I try to hit http://localhost/help/test

like image 514
JamesE Avatar asked Jun 25 '26 10:06

JamesE


1 Answers

I think some of your confusion is coming from the require in app.js. Let's look at this line:

var help = require('./routes/help');

That line loads the module in routes/help.js. This file is non-existent In your current configuration. Rename your ./routes/index.js file to ./routes/help.js.

Since the above file will only handle routes prefixed with /help and not /help/test, will need to have an additional require:

var help_test = require('./routes/test');

Your app.js file should now have the following:

var help = require('./routes/index');
var help_test = require('./routes/test');

var app = express();
app.use('/help', help);
app.use('/help/test', help_test);

It should be noted that since your help_test module defines a path at /test, and you "use" it at /help/test, the final path of that route will be: /help/test/test.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!