Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Binding a route to '/' is responding to all 404s in Express?

Binding a route to '/' is responding to all 404s in Express?


Hi I'm new to node and I'm having a routing issue with Express. I'm trying to create a mini MVC framework to create test projects with and learn node/noSQL. Most of the code is based off the MVC example ( in the Express repo. In addition to that I've added Extendable Controllers with help from here: How to create extendable controllers in ExpressJS


The problem is in lines 33-43.

if ( key == 'index' && name == 'main' ) {
    method = 'get';
    path = '/';
else if ( key == 'index' ) {
    method = 'get';
    path = '/' + name;
else {
    throw new Error( 'unrecognized route: ' + name + '.' + key );

What I'm trying to do in this block is assign the Main controller to respond to localhost/ and every other controller to respond to localhost/controller/. If I change line 35 to /main (instead of /) then 404's will correctly fall through the boot and into the error handler in app/index.js:

// load controllers
require( './boot' )( app, { verbose: !module.parent } );

// assume "not found" in the error msgs is a 404
app.use( function( err, req, res, next ) {
    // treat as 404
    if ( ~err.message.indexOf( 'not found' ) ) return next( );

    // log it
    console.error( err.stack );

    // error page
    res.status( 500 ).render( '5xx' );

With the code as is, if I go to any Invalid Url, localhost/deep, localhost/doop they all return the main module? For some reason it looks like binding to '/' makes any invalid URL use this route?

Any ideas on what I'm doing wrong? Thanks!

Problem courtesy of: Jonathan


Changing app.use to app.all fixed the problem. Does anyone know what the difference is?

Solution courtesy of: Jonathan


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Binding a route to '/' is responding to all 404s in Express?


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription