如何解决每个请求中间件的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,next) {
next();
};
app.get(\'/user\',func,response) {
response.writeHead(200);
response.end(\'Okay\');
});
这也有相同的结果。
解决方法
function(request,response,callback) {
与
next();
您应该将callback
更改为next
,反之亦然。
,我找到了此链接。
Express中间件:基本HTTP身份验证
作者似乎在做与您相同的事情,除了他在next()之后有一个返回。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。