我正在尝试将404页面添加到我的快速应用程序中,但是一旦我将路由添加到404页面,静态文件就不会呈现(例如无法获取'stylesheet / main.css')。
建议总是将任何404页面作为最后一条路由,我已经这样做了,但它仍然为任何静态内容提供了404页面(但不包括其他路由)。如果我删除//Add 404 page for unknown routes
评论下面的函数,一切正常。
为什么这样做以及我该怎么做才能纠正它?
以下代码:
//modules
var express = require('express'),
path = require('path'),
errorPages = require('./controllers/errorPages.js');
//start express
var app = express();
// set-up environment
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('secret code...'));
app.use(express.session());
//Redirect to login for all requests if user is not logged in at /dash
app.use('/dash', function(req, res, next) {
if(!req.session.auth) {
res.location('/login');
res.send(307, null);
}
next();
});
app.use(app.router);
app.use(require('less-middleware')(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//start routes from routes.js file
require('./routes')(app);
//Add 404 page for unknown routes
app.all('*', function(req, res) {
errorPages.get(req, res, 404);
});
app.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
答案 0 :(得分:1)
而不是
//Add 404 page for unknown routes
app.all('*', function(req, res) {
errorPages.get(req, res, 404);
});
使用此
app.use(function(req, res, next){
errorPages.get(req, res, 404);
});
并在最后添加此中间件。