3

ここに示されているように、Node.jsでExpress用の非常に単純なBasic Authミドルウェアを実行しようとしています: http://node-js.ru/3-writing-express-middleware

私はミドルウェア機能を持っています:

var basicAuth = function(request, response, next) {
    if (request.headers.authorization && request.headers.authorization.search('Basic ') === 0) {
        // Get the username and password
        var requestHeader = new Buffer(
                request.headers.authorization.split(' ')[1], 'base64').toString();
        requestHeader = requestHeader.split(":");

        var username = requestHeader[0];
        var password = requestHeader[1];

        // This is an async that queries the database for the correct credentials
        authenticateUser(username, password, function(authenticated) {
            if (authenticated) {
                next();
            } else {
                response.send('Authentication required', 401);
            }
        });
    } else {
        response.send('Authentication required', 401);
    }
};

そして、私は私のルートを持っています:

app.get('/user/', basicAuth, function(request, response) {
    response.writeHead(200);
    response.end('Okay');
});

このリクエストをカールしようとすると、次のようになります。

curl -X GET http://localhost/user/ --user user:password
Cannot GET /user/

createServer() の呼び出し中にミドルウェアを追加すると、これは非常にうまく機能しますが、このルートのようにリクエストごとに実行すると、サーバー側で静かに停止します。残念ながら、すべてのリクエストで認証が必要なわけではないため、これをグローバル ミドルウェアにすることはできません。

Express をオフにして Connect を使用してみましたが、同じ結果が得られたので、そこに何かがあると思います。誰もこれを経験したことがありますか?

編集:関連するコードを徹底的にログに記録し、 next が呼び出されていることにも言及する必要がありますが、どこにも行かないようです。

編集2:記録のために、「空の」ミドルウェアもサイレントに失敗します:

var func = function(request, response, next) {
    next();
};

app.get('/user', func, function(request, response) {
    response.writeHead(200);
    response.end('Okay');
});

これも同じ結果です。

4

2 に答える 2

0

このリンクを見つけました。

Express ミドルウェア: 基本 HTTP 認証

著者は、next() の後にリターンがあることを除いて、あなたと同じことをしているようです。

于 2011-05-28T20:31:54.497 に答える
0

function(request, response, callback) {

next();

に変更callbackするnextか、その逆にする必要があります。

于 2011-04-15T20:34:07.487 に答える