我有一些代码如下所示:
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");
});
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我无法访问/ public静态目录中的任何内容:所有内容都被404路由捕获.我错过了一些关于它应该如何工作的东西吗?
Ray*_*nos 13
你在做
app.use(app.router);
app.use(express.static(__dirname + "/public"));
Run Code Online (Sandbox Code Playgroud)
你想做的是
app.use(express.static(__dirname + "/public"));
app.use(app.router);
Run Code Online (Sandbox Code Playgroud)
因为你有一个捕获app.router
它的所有路线必须低于其他任何东西.否则,catch all route将确实捕获所有内容,其余的中间件将被忽略.
作为旁边的捕获,所有这样的路线都很糟糕.
一个更好的解决方案是在调用app.use之后放置以下代码:
app.use(function(req, res) {
res.send(404, 'Page not found');
});
Run Code Online (Sandbox Code Playgroud)
或类似的功能.
这样做而不是使用 app.get("/*", ...
我这样做的方式略有不同.如果查看静态文件服务器的中间件代码,它允许调用错误调用的回调函数.只有catch你需要响应对象将有用的东西发送回服务器.所以我做了以下事情:
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});
}
});
});
Run Code Online (Sandbox Code Playgroud)
基本上发生的是,如果有错误,它会呈现我漂亮的错误页面并记录一些东西,以便我可以在某处调试.
归档时间: |
|
查看次数: |
11528 次 |
最近记录: |