2

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 ステートメントが起動し、同様に次の case 自体とその下のすべてが起動します。したがって、「/foo」は「foo」を起動し、コンソールに 404 を書き込みますが、404 ページは表示されません (もちろん、悪い URL をまったく使用しない限り)。

ケースが適切に動作しないように見える理由を理解しようとしています。どんな助けでも大歓迎です!

4

1 に答える 1

1

breakの間にステートメントがありません。caseJavaScriptswitchステートメントは、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"); 
}
于 2013-09-28T20:01:18.607 に答える