Note. For all these examples, I use an application structured as follows:
.
├── app.js
└── public
├── protected
│ └── file.txt <-- contains text "protected file"
└── regular
└── file.txt <-- contains text "regular file"
You have several options. The simplest one is to Express route the request through your router before the public middleware, allowing you to intercept the request:
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
function userIsAllowed(callback) {
callback(false);
};
app.get('/', function(req, res, next) {
res.end('Home page');
});
app.get('/protected/*', function(req, res, next) {
userIsAllowed(function(allowed) {
if (allowed) {
next();
} else {
res.end('You are not allowed!');
}
});
});
http.createServer(app).listen(3000, function(){
console.log('Express server listening on port 3000');
});
Results:
http://localhost:3000/regular/file.txt # regular file
http://localhost:3000/protected/file.txt # You are not allowed!
, , , , ( ).
- , , :
var express = require('express');
var http = require('http');
var path = require('path');
function userIsAllowed(callback) {
callback(false);
};
var protectPath = function(regex) {
return function(req, res, next) {
if (!regex.test(req.url)) { return next(); }
userIsAllowed(function(allowed) {
if (allowed) {
next();
} else {
res.end('You are not allowed!');
}
});
};
};
var app = express();
app.use(protectPath(/^\/protected\/.*$/));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.end('Home page');
});
http.createServer(app).listen(3000, function(){
console.log('Express server listening on port 3000');
});
, , , URL , . , , .
:
http://localhost:3000/regular/file.txt # regular file
http://localhost:3000/protected/file.txt # You are not allowed!