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 - 如何使用 Nodejs 在没有 OAuth 的情况下使用 Google Drive API?

node.js - 如何在 NodeJS 和 Express 中使用 Angular 包?

node.js - connect.js 中间件的正确顺序?

html - 将 Shell 脚本变量输出为 HTML

node.js - 在 BrowserSync Node 中手动触发刷新

android - App Engine 中运行的是哪种类型的服务器?

javascript - 服务器端代码 Node 内的套接字发出

express - 为什么我们需要在express.js服务器上使用代理才能获得与react-routing相结合的webpack热重载服务器功能

node.js - 使用来自 emberJs 的参数过滤器进行快速路由

node.js - 如何使用 KrakenJS 将 Redis 配置为 session 存储