ExpressJS: How do I ignore public static files on my route?

app.get("/:name?/:group?", function(req, res){... 

matches the files that are in my public directory. Therefore, if I include a stylesheet:

 <link type="text/css" href="/stylesheets/style.css" /> 

Node will match /stylesheets/style.css and set name to stylesheets and group to style.css.

What is the best way to avoid this?

+7
source share
3 answers

The easiest way is to make sure that express runs the static provider middleware before the router middleware. You can do this by following these steps:

 app.use(express.static(__dirname + '/public')); app.use(app.router); 

Thus, the static file will find it and respond, and the router will not execute. I had the same confusion with the default router position (last) with my compilation of coffeescript files. FYI has the docs on this here (find the app.router page and you will see an explanatory paragraph.

+21
source

You may also have a reverse proxy, for example Nginx process static files for you. I believe that many professional Node / Ruby on Rails settings do this this way.

+2
source

For those who need it, my solution used Middleware. If anyone finds a better solution, please let me know!

 public = ['images', 'javascripts', 'stylesheets', 'favicon.ico'] ignore = (req, res, next) -> if public.indexOf(req.params.name) != -1 console.log "Ignoring static file: #{req.params.name}/#{req.params.group}" next('route') else next() app.get "/:name?/:group?", ignore, (req, res) -> ... 
+1
source

All Articles