【问题标题】:Using express.static middleware in an authorized route在授权路由中使用 express.static 中间件
【发布时间】:2012-07-13 11:25:43
【问题描述】:

我正在使用带有 express 和 passportjs 的节点来限制对位于私有文件夹中的文件的访问。我已将我的代码减少到以下内容。 公共静态文件夹中的所有内容都运行良好,但通过使用 staticMiddleware 定位私有文件夹的路由返回 404 错误。

var express = require('express')
,   util = require('util');

var app = express.createServer();
var staticMiddleware = express.static(__dirname + '/private');

app.configure(function() {
  app.use(app.router);
  app.use(express.logger('dev')); 
  app.use('/public',express.static(__dirname + '/public'));
});

app.get('/private/:file', function(req, res, next){
    console.log('about to send restricted file '+ req.params.file);
    staticMiddleware(req, res, next);
});
app.listen(16000);

我使用了以下似乎对其他人有用的参考资料,所以我一定遗漏了一些东西。 它不适用于我只显示位于私人区域的内容的 404 响应。

Node.js module-specific static resources

NodeJS won't serve static files, even when using express.static

Redirecting to a static file in express.js

我可以发誓我以前有这个工作,也许它在新版本的某些东西中被破坏了。

  • 节点 v0.8.1
  • npm 1.1.12
  • express@2.5.11
  • connect@1.9.2

【问题讨论】:

  • 我正在寻找完全相同的东西。关于如何做到这一点有一些想法,但感谢您自己回答。这是一个非常好的解决方案。

标签: node.js express connect


【解决方案1】:

一直盯着我看

app.get('/private/:file', function(req, res, next){
    console.log('about to send restricted file '+ req.params.file);
    req.url = req.url.replace(/^\/private/, '')
    staticMiddleware(req, res, next);
});

2014 年 11 月 29 日编辑

因此,在有人发布了这个问题后,我回到这个答案,发现即使我提到了 passportjs,我也从未展示过我最终是如何使用这个功能的。

var staticMiddlewarePrivate = express['static'](__dirname + '/private');

app.get('/private/*/:file', auth.ensureAuthenticated, function(req, res, next){
    console.log('**** Private ****');
    req.url = req.url.replace(/^\/private/, '');
    staticMiddlewarePrivate(req, res, next);
});

【讨论】:

    【解决方案2】:

    您还可以将express.static(__dirname + '/private'); 添加到您的 app.config。

    app.configure(function() {
      app.use(app.router);
      app.use(express.logger('dev')); 
      app.use('/public',express.static(__dirname + '/public'));
      app.use('/private',express.static(__dirname + '/private'));
    });
    

    private 路径中间件将在任何以 private 开头的路径时执行。

    【讨论】:

    • 这将正确地公开静态文件,但不会对它们进行密码保护。我的理解是@eephillip 想让他们得到服务,但也希望通过 passwordJS 保护密码。
    猜你喜欢
    • 2015-03-24
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2017-09-03
    相关资源
    最近更新 更多