【问题标题】:Authenticate before serving up directory in Express在 Express 中提供目录之前进行身份验证
【发布时间】:2014-12-04 18:10:02
【问题描述】:

在用户查看快速目录文件树之前尝试对用户进行身份验证时遇到问题。即使我在下载文件之前通过了身份验证路由,我也可以在所有其他页面上进行身份验证,但不能在“/dat/:file(*)”上进行身份验证。 因此,当用户转到“/”时,如果他们未登录,express 将重定向他们。但是,如果用户转到“/dat”,express 将不会进行身份验证并允许他们浏览文件树。我正在使用 express@3.4.8,任何帮助都会很棒。谢谢!

app.configure( function() {
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');

    app.use('/', express.static(__dirname + '/public'));
    app.use('/dat', express.directory(__dirname + '/public/dat', {hidden: true, icons: true}));

    app.use(express.json());
    app.use(express.urlencoded());
    app.use(express.methodOverride());
    app.use(express.cookieParser('secret'));
    app.use(express.session({
        secret: 'secret',
        maxAge: 3600000
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(app.router);
});

app.get('/', ensure_authenticated, routes.index);
app.get('/dat/:file(*)', ensure_authenticated, function(req, res, next) {
    var path = __dirname + '/' + req.params.file;
    res.download(path);
});

【问题讨论】:

    标签: javascript node.js authentication express routes


    【解决方案1】:

    中间件的顺序很重要。

    app.use('/dat', express.directory(__dirname + '/public/dat', {hidden: true, icons: true}));
    

    之前:

    app.get('/dat/:file(*)', ensure_authenticated, function(req, res, next) {
        var path = __dirname + '/' + req.params.file;
        res.download(path);
    });
    

    因此,第一个中间件正在处理请求。

    app.use(app.router)) 之后移动第一条路线应该可以解决这个问题。

    如果您还希望用户通过身份验证以查看目录列表,您还需要将 ensure_authenticate 添加到 express.directory 的路由中。

    app.use('/dat', ensure_authenticate, express.directory ...
    

    【讨论】:

    • 感谢 Jordonias,这是有道理的,它会在将您路由到“/dat”之前要求进行身份验证。但是,现在当我进行身份验证然后转到“/dat”时,它会尝试提供静态 html 文件而不是文件树...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    相关资源
    最近更新 更多