express 4.x 打开网页时弹出登录对话框

//打开网页时弹出登录对话框
app.use(function(req, res, next) {
    var auth = req.headers['authorization'];
    if(auth) {
        var tmp = auth.split(' ');
        var buf = new Buffer(tmp[1], 'base64');
        var plain_auth = buf.toString();
        var creds = plain_auth.split(':');
        var username = creds[0];
        var password = creds[1];
        if((username == 'admin') && (password == 'admin')) {
            //认证成功,允许访问
            return next();
        }
    }

    //要让浏览器弹出登录对话框,必须将status设为401,Header中设置WWW-Authenticate
    res.set('WWW-Authenticate', 'Basic realm=""');
    res.status(401).end();
});
 

猜你喜欢

转载自blog.csdn.net/F2004/article/details/51918396