每个请求连接/快速中间件在某处失败

时间:2011-04-15 20:19:35

标签: node.js connect express

我正在尝试为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,我得到了相同的结果,所以我认为它就在那里。有没有人经历过这个?

编辑:我还应该提一下,我已经详尽地记录了相关代码,接下来正在调用,但它似乎无处可去。

编辑2:对于记录,“空”中间件也无声地失败:

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

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

这也有相同的结果。

2 个答案:

答案 0 :(得分:0)

function(request, response, callback) {

VS

next();

您应该将callback更改为next或反之亦然。

答案 1 :(得分:0)

我找到了这个链接。

Express middleware: Basic HTTP Authentication

作者似乎和你做了同样的事情,除了他在下一个()之后返回。

相关问题