我正在尝试在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 这个请求,我会得到:
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');
});
这也有同样的结果。
2条答案
按热度按时间nwwlzxa71#
function(request, response, callback) {
vs
next();
您应该将
callback
更改为next
或反之亦然。r7s23pms2#
我发现了这个链接。
Express middleware: Basic HTTP Authentication
作者似乎在做和你一样的事情,除了他在下一个()之后有一个返回。