我知道有很多Node JS路由器框架,但我试图从方方面面开始学习概念而不是重用代码。简而言之,我非常简单的路由器正在部分工作,但有一些问题。这是代码。
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." );
}
路由器代码:
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");
}
}
默认和/或404部分工作正常,但其他部分没有。基本上,如果我请求索引页面“/”所有case语句都会触发,同样下一个案例会激活它自己以及它下面的所有内容。因此,“/ foo”触发“foo”并将404写入控制台,但我没有得到404页面(除非我当然使用了一个错误的URL)。
试图理解为什么案件似乎表现不正常。任何帮助将不胜感激!
答案 0 :(得分:1)
您在break
条款之间遗漏了case
条款。 JavaScript switch
语句从C语言和其他类似语言中借用它们的行为,并且“堕落”行为是它应该工作的方式(尽管这可能看起来像一个可怕的想法)。
因此:
switch(pathname) {
case '/':
console.log("Request for path '/'");
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("In Index!");
break;
case '/start':
console.log("Request for path '/start'");
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("In Start!");
break;
case '/foo':
console.log("Request for path '/foo'");
res.writeHead(200, {"Content-Type": "text/plain"});
res.write("In Foo!");
break;
default: // Default code IS working
console.log("404");
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("Default 404");
}