我正在使用Express 4,我有大约50个html页面.我正在尝试处理404错误,但无法弄清楚如何.我不想手动定义节点内的所有路由器.如果页面不存在,有没有办法动态重定向到404 Jade模板?
我试过这段代码但是没有用:
app.enable('verbose errors');
app.set('port', 3000);
app.use(express.static(__dirname + '/html/'));
var server = http.createServer(app);
server.listen(app.get('port'), function() {
console.log('ONLINE !');
});
app.use(function(req, res, next) {
console.log('GET ' + req.originalUrl)
console.log('At %d', Date.now());
next();
});
// Handle 404
app.use(function(req, res, next) {
if(req.accepts('html') && res.status(404)) {
res.render('404.jade');
return;
}
});
Run Code Online (Sandbox Code Playgroud)
sha*_*raj 12
这对我有用:
var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.get('/employee', function (req, res) {
res.send('Employee route !!');
});
// Handle 404 - Keep this as a last route
app.use(function(req, res, next) {
res.status(404);
res.send('404: File Not Found');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Run Code Online (Sandbox Code Playgroud)
文件夹结构,
现在我们发出这样的请求
这已由中间件处理.
UPDATE
在不编写get请求的情况下显示html文件的方法就是这样的另一个中间件
app.use(express.static('public'));
app.use(express.static('views'));
Run Code Online (Sandbox Code Playgroud)
在'public'之后添加'views'中间件.
现在,如果我们给
页面呈现.
归档时间: |
|
查看次数: |
10464 次 |
最近记录: |