快速静态目录如何与 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 路由捕获。我是否遗漏了一些关于它应该如何工作的信息?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你正在做的
事情你想要做的是,
因为你在
app.router
中有一个捕获所有路由,所以它必须比其他任何东西都低。否则,catch all 路由确实会捕获所有内容,而中间件的其余部分将被忽略。顺便说一句,所有这样的路线都很糟糕。
You're doing
What you want to do is
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.
更好的解决方案是将以下代码放在对 app.use 的所有调用之后:
或类似的函数。
执行此操作而不是使用
app.get("/*", ...
A better solution would be to place the following code after all calls to app.use:
Or a similar function.
Do this instead of using
app.get("/*", ...
我的做法略有不同。如果您查看静态文件服务器的中间件代码,它允许调用一个出现错误的回调函数。唯一的问题是您需要响应对象将有用的内容发送回服务器。所以我执行以下操作:
基本上,如果出现错误,它会呈现我漂亮的错误页面并记录一些内容,以便我可以在某个地方进行调试。
I'm doing it a slightly different way. If you look at the middleware code for the static file server it allows for a callback function that gets called with errors. Only catch is you need the response object to send something useful back to the server. So I do the following:
Basically what happens is if there is an error it renders my pretty error page and logs something so that I can debug somewhere.