baseprime / grapnel

The smallest JavaScript router with named parameters, HTML5 pushState, and middleware support
http://grapnel.js.org
467 stars 40 forks source link

state.parent() does not return false when no route is matched #67

Closed linoliveira closed 5 years ago

linoliveira commented 7 years ago

I am using the grapnel-server router on node 6.6 to create a simple REST API. Following the docs to handle 404 the this.state.parent() should return false when no other routes are matched. In the first request from a client the function this.state.parent() returns false as expected, but in the following requests from the same client to the same 'not defined' route the this.state.parent() returns the CallStack. According to the docs linked above, it should always return false when no other routes are matched, or did I miss something?

The workaround to this unexpected behavior was add a condition to the if statement as follows:

// This should be your last route
app.all('*', function(req, res){
    let parent = this.state.parent();
    if(!parent || parent.route == '*'){
        res.writeHead(404);
        res.end('404');
    }
});

I am not quite sure about the reliability of this solution in the long term though. Please advise. Thanks!