Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do express static directories work with a 404 route?

I have some code that looks like the following:

app.configure(function() {
   app.set("views", __dirname + "/views");
   app.set("view engine", "ejs");
   app.use(express.bodyParser());
   app.use(express.methodOverride());
   app.use(express.logger()); 
   app.use(app.router);
   app.use(express.static(__dirname + "/public"));
});

//Routes
app.get("/", function(req, res) {
    res.render("index.ejs", {locals: {
      title: "Welcome"
    }});
});

//Handle 404
app.get("/*", function(req, res, next) {
    next("Could not find page");
});

The problem I have is that I can't access anything in the /public static directory: everything gets caught by the 404 route. Am I missing something about how this is supposed to work?

like image 701
Jim Wang Avatar asked Oct 21 '11 00:10

Jim Wang


1 Answers

You're doing

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

What you want to do is

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

Since you have a catch all route in app.router it must be lower then anything else. otherwise the catch all route will indeed catch everything and the rest of the middleware is ignored.

As an aside catch all routes like that are bad.

like image 171
Raynos Avatar answered Oct 04 '22 21:10

Raynos