Thursday, 16 March 2017

ExpressJS Router is not handling root routes

I have a very simple ExpressJS application on which all of the "roots" in each and every single route other than home are not being handled and they always display an empty JSON object on the page.

In some posts it was mentioned that it could be a caching issue since these routes always return a 304 status, but I've tried doing an "Empty cach and hard reload" on Chrome and even with the 200 status I still get a blank page with an empty JSON object displayed on it. I tried it with MS Edge and got the exact same behavior.

Here's what I have:

On my app file

var app = express();

var home = require('./routes/home');
var adventure = require('./routes/adventure');
var test = require('./routes/test');

app.use('/', home);
app.use('/adventure', adventure);
app.use('/test', test);

On home.js file:

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

router.get('/', (req, res) => {
   console.log("This works fine with http://localhost:3000.");
   res.render('home');
});

module.exports = router;

On the adventure.js file:

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

router.use('/:id', (req, res) => {
   console.log("This works fine with http://localhost:3000/adventure/5.");   
   next();
});

router.get('/:id', (req, res) => {
   console.log("This works fine with http://localhost:3000/adventure/5."); 
   res.render('adventure');
});

//I've also tried putting this before the other routes and the result is the same.
router.get('/', (req, res) => {
   console.log("This is never written in the console with http://localhost:3000/adventure.");
   res.render("This is never rendered in the page.");
});

On the test.js file:

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

router.use('/', (req, res) => {
    console.log("This is never written on the console with http://localhost:3000/test.");
    res.send("Hello from the test root route");
});

module.exports = router;

In the ExpressJS Router documentation and every single blog and example I've found it says that this is how it should work so I am really at a loss here.

Thank you.



via Sergio Romero

No comments:

Post a Comment