开发者

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

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

is matching 开发者_运维问答files that are in my public directory. So if I include a stylesheet:

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

Node will match /stylesheets/style.css and assign name the value stylesheets and group the value style.css.

What's the best way to avoid this?


The easiest thing may be to make sure that express runs the static provider middleware prior to the router middleware. You can do this by doing:

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

That way the static file will find it and respond and the router won't be executed. I've had similar confusion with the router's default position (last) screwing up with my compilation of coffeescript files. FYI there are docs on this here (search the page for app.router and you'll see an explanatory paragraph.


For anyone who may need it, my solution was using 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) -> ...


You could also have a reverse proxy like Nginx handle the static files for you. I believe many professional Node / Ruby on Rails setups do it this way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜