看来用Express v3实现基本HTTP身份验证很简单:
app.use(express.basicAuth('username', 'password'));
不过,版本4(我使用的是4.2)删除了basicAuth
中间件,所以我有点卡住了.我有以下代码,但它不会导致浏览器提示用户输入凭据,这正是我想要的(我认为旧方法会这样做):
app.use(function(req, res, next) {
var user = auth(req);
if (user === undefined || user['name'] !== 'username' || user['pass'] !== 'password') {
res.writeHead(401, 'Access invalid for user', {'Content-Type' : 'text/plain'});
res.end('Invalid credentials');
} else {
next();
}
});