简体   繁体   English

一旦添加404页面,Express不会呈现静态文件

[英]Express does not render static files once 404 page is added

I am trying to add a 404 page to my express application, however once I add the route to the 404 page, the static files do not render (eg cannot get 'stylesheet/main.css'). 我试图将404页面添加到我的express应用程序中,但是,一旦我将路由添加到404页面,静态文件就不会呈现(例如,无法获取“ stylesheet / main.css”)。

The advice is always to put any 404 pages as the very last route, which I have done so and yet it still gives a 404 page for any static content (but not for other routes). 建议始终将所有404页作为最后一条路由,尽管我这样做了,但仍然为任何静态内容提供了404页(但其他路由则没有)。 It all works fine if I remove the function below the //Add 404 page for unknown routes comment. 如果我删除//Add 404 page for unknown routes注释功能,则一切正常。

Why is this and what can I do to rectify it? 为什么会这样,我该怎么做才能纠正它?

Code below: 代码如下:

//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'));
});

Instead of 代替

//Add 404 page for unknown routes
app.all('*', function(req, res) {
   errorPages.get(req, res, 404);
});

Use this 用这个

app.use(function(req, res, next){
    errorPages.get(req, res, 404);
});

and Add this middleware in the last. 最后添加此中间件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM