开发者

Connect/Express per request middleware is failing somewhere

I'm trying to do a very simple Basic Auth middleware for Express on Node.js as demonstrated here: http://node-js.ru/3-writing-express-middleware

I have my middleware function:

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.authorizatio开发者_StackOverflow社区n.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);
    }
};

And I have my route:

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

If I try to curl this request I get:

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

This works totally cool when I add the middleware while calling createServer(), but when I do it per-request like I am in this route, it just dies quietly server-side. Unfortunately, since not all requests require authentication, I can't make this a global middleware.

I've tried flipping off Express and just using Connect and I get the same result, so I assume it's something in there. Has anybody experienced this before?

Edit: I should also mention that I've logged the relevant code exhaustively and next is being called, but it just appears to go nowhere.

Edit 2: For the record, an "empty" middleware also fails silently:

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

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

This also has the same result.


function(request, response, callback) {

vs

next();

Your supposed to either change callback to next or vica versa.


I found this link.

Express middleware: Basic HTTP Authentication

The author seems to be doing the same thing as you did, except he has a return after the next().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜