5

node.jsの学習を始めたばかりです。次の(サーバー)サンプルがあります:


var app = require("express").createServer();
app.listen(80);

function fail(req, res, next) { setTimeout(next, 10); }
function success() {
    return function(req, res, next) { setTimeout(next, 10); };
}
app.get("/success0", success(), function(req, res, next) { res.send("0"); });
app.get("/success1", success(), function(req, res, next) { res.send("1"); });
app.get("/fail0", fail, function(req, res, next) { res.send("0"); });
app.get("/fail1", fail, function(req, res, next) { res.send("1"); });

/fail0 と /fail1 を同時に呼び出すと、一方は成功し、もう一方は 404 エラーで失敗します。ただし、/success0 と success1 を呼び出しても機能します。誰かがなぜ一方が機能し、もう一方が機能しないのかを教えてもらえますか? 以下は私のテストクライアントです:


var http = require("http");
var sys = require("sys");

for(var i = 0; i < 10; i++) {
    var io = http.createClient(80, "localhost");
    var request = io.request("GET", "/fail" + (i%2), {host:"localhost"});
    request.on("response", function(response) {
        var body = "";
        response.on("data", function(data) { body += data; });
        response.on("end", function() {
            sys.puts(response.statusCode + ":" + body);
        });
    }).end();
}

上記のクライアントを実行すると、次のように返されます。

404:取得できません /fail0
200:1
404:取得できません /fail0
200:1
404:取得できません /fail0
200:1
404:取得できません /fail0
200:1
404:取得できません /fail0
200:1
4

1 に答える 1

1

Here is an explanation of this bug (and a pointer to a fix follows below).

The reason is that the routing logic of the Connect library stores state (the current route's index) as a property in the function callback. In your test case, when the callback is registered for the second route, '/fail1', this one overrides the state set by the route for '/fail0'. An incoming request for fail0 therefore fails.

This bug was reported on the express mailing list in this thread.

A fix was committed in this fork.

于 2011-03-11T21:50:21.610 に答える