快速静态目录如何使用404路由?

我有一些如下所示的代码:

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"); }); 

我遇到的问题是我无法访问/ public静态目录中的任何东西:所有东西都被404路由所捕获。 我是否错过了这个应该如何工作?

你在做

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

你想要做的是

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

既然你在app.router有所有的路线,它必须低于其他任何东西。 否则捕获所有的路由将确实抓住一切,其余的中间件被忽略。

顺便说一下,所有这样的路线都很糟糕。

更好的解决scheme是在app.use的所有调用之后放置以下代码:

 app.use(function(req, res) { res.send(404, 'Page not found'); }); 

或者有类似的function。

这样做,而不是使用app.get("/*", ...

我做了一个稍微不同的方式。 如果您查看静态文件服务器的中间件代码,它允许调用具有错误的callback函数。 只有抓住你需要的响应对象发送一些有用的东西回到服务器。 所以我做了以下几点:

 var errMsgs = { "404": "Dang that file is missing" }; app.use(function(req, res, next){ express.static.send(req, res, next, { root: __dirname + "/public", path: req.url, getOnly: true, callback: function(err) { console.log(err); var code = err.status || 404, msg = errMsgs["" + code] || "All is not right in the world"; res.render("error", { code: code, msg: msg, layout: false}); } }); }); 

基本上会发生什么,如果有一个错误,它会呈现我漂亮的错误页面,并logging一些东西,以便我可以debugging的地方。