Reputation:
When writing my node.js with express server I would like to first have the route middleware run before static middleware (want to have full control over the req/res before static content is being served).
Now, I am also using a route matching on * at the end to simply return with a 404. Obviously, since I am not having routes for the static content, I need to add routes for my static (public) folder. When doing so, I would like to pass control from inside the route to the static middleware and thereby skip my 404 route. Is that possible? I read I could call next("route"), but this gives me the same result as calling next().
Thanks
Upvotes: 1
Views: 2427
Reputation: 145994
You don't need to add a *
route explicitly. Express will do a 404 for you.
All you need to do is tell express to run the custom routes before the static middleware. You do this like so:
app.use(app.router);
app.use(express.static(__dirname + '/public');
Upvotes: 3
Reputation: 1539
I'm not sure if this helps, but if what you want is selectively log or deny the static file downloads you can do this:
First, Ensure the routing is executed before the static middleware:
app.configure(function(){
...
app.use(app.router); // this one goes first
app.use(express.static(__dirname + '/public'));
...
Second, register a route that catches all the requests and just respond conditionally. The following example detects and log a message when file-A.txt (which filesystem path is /public/file-A.txt) will be downloaded, any other file request will download with no interruption:
app.get('/*', function(req, res, next){
if(req.params[0] === 'file-A.txt') { // you can also use req.uri === '/file-A.txt'
// Yay this is the File A...
console.warn("The static file A has been requested")
// but we still let it download
next()
} else {
// we don't care about any other file, let it download too
next()
}
});
That's it, I hope this helps.
Upvotes: 0