Saturday, 28 September 2013

Simple NodeJS Router Issues -- Misbehaving Case Statement?

Simple NodeJS Router Issues -- Misbehaving Case Statement?

I know that there are plenty of Node JS router frameworks out there, but
I'm trying to start from square one and learning the concept rather than
reuse code. In short, my extremely simple router is working part way but
has some issues. Here is the code.
function serverStart(urlRoute) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request received for " + pathname + ".");
urlRoute(pathname, request, response);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started." );
}
Router code:
function urlRoute(pathname, req, res) {
console.log(pathname)
switch(pathname) {
case '/':
console.log("Request for path '/'");
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("In Index!");
case '/start':
console.log("Request for path '/start'");
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("In Start!");
case '/foo':
console.log("Request for path '/foo'");
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("In Foo!");
default: // Default code IS working
console.log("404");
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("Default 404");
}
}
The default and/or 404 section works fine, but the others do not.
Basically, if I request the index page "/" all case statements fire, and
similarly the next case fires itself and everything below it. So, "/foo"
fires "foo" and writes out 404 to the console, but I don't get a 404 page
(unless of course I use a bad URL altogether).
Trying to understand why the case doesn't seem to behave properly. Any
help would be appreciated!

No comments:

Post a Comment