I’m trying to build a webapp where:
http://example.com/static/x.png serves x.png as a static file using Connect’s static middleware
http://example.com/other_stuff does other stuff
My directory structure is
start_server.coffee
static/
x.png
In start_server.coffee I have:
app = connect()
app.use connect.staticCache()
app.use connect.static(__dirname + '/static')
app.use ...middleware that serves the dynamic parts of my app...
app.listen 80
When I try http://example.com/static/x.png, the request bypasses the static server and gets routed to the rest of my app. I stepped through the code in a debugger and it looks like static is trying to lookup static/static/x.png instead of static/x.png.
I was able to get it working by changing connect.static(__dirname + ‘/static’) to connect.static(__dirname), but now it will serve stuff that’s not in the static directory which is not good!
What’s the cleanest way of doing what I’m trying to do? I could probably use Express’s routing functionality, but I don’t particularly want to use Express unless I have to, since the rest of my app handles routing its own way.
So the issue is the mismatch between your URL paths and your filesystem layout. There are 2 easy-peasy get-on-with-your-life solutions.
staticdirectory but the URLs won’t include the word “static”.mkdir public && mv static public. Leave thepublicdirectory empty other than thestaticsubdirectory. Now your URLs can stay the same and in your code you needapp.use connect.static(__dirname + '/public').Now this is what the static middleware provides out of the box. The URLs have to map simply to the filesystem. This is why it “just works” and is simple.
If you really want to have
static/in your URL but not map to a directory underneath your static root, add a middleware before the static middleware that alters req.path to remove the leading “/static”, then callnext()and I think that will trick the static middleware into doing what you want.