Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

node.js - Using express.static middleware in an authorized route

I'm using node with express and passportjs to restrict access to files located in a private folder. I have reduced my code to the following. Everything in the public static folder works great but route targeting the private folder through the use of the staticMiddleware returns 404 errors.

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

I was using the following references that seems to work for others, so I must be missing something. It won't work for me showing only 404 responses for the content located in the private area.

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

I could have sworn I had this working before, maybe it was broken in a new version of something.

  • Node v0.8.1
  • npm 1.1.12
  • express@2.5.11
  • connect@1.9.2
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

sheesh staring at me the whole time

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

Edit 11-29-2014

So after someone posted to the question I came back to this answer to find that even though I mention passportjs I never showed how I ended up using this function.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...