node.js - 在授权路由中使用 express.static 中间件

标签 node.js express connect

我正在使用带有 express 和 passportjs 的 Node 来限制对位于私有(private)文件夹中的文件的访问。我已将我的代码减少到以下内容。 公共(public)静态文件夹中的所有内容都运行良好,但通过使用 staticMiddleware 定位私有(private)文件夹的路由返回 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);

我使用了以下似乎对其他人有用的引用资料,所以我一定遗漏了一些东西。 它不适用于我只显示位于私有(private)区域的内容的 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

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

  • Node v0.8.1
  • npm 1.1.12
  • express@2.5.11
  • connect@1.9.2

最佳答案

一直盯着我看

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);
});

关于node.js - 在授权路由中使用 express.static 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11473399/

相关文章:

node.js - 如何将自定义证书颁发机构 (CA) 添加到 nodejs

node.js - 在nodejs中使用thrift进行客户端多路复用

javascript - Express Node JS POST。如何在不使用 url 参数的情况下向 req.body 添加值

javascript - 通过中间件以express方式访问get请求

connect - Debezium 连接器将 kafka key 作为 avro 插入?

javascript - 如何防止用户使用 express 访问客户端 html 文件?

node.js 和 nginx 代理设置——出了点问题,但是什么?

javascript - 使用 React 将选项卡设置为事件状态

javascript - jQuery/Javascript - 如何在按钮的值更改时触发事件?