这是我的代码:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/test-angular.html');
})
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.sendFile(__dirname + '/public/error.html');
});
var server = app.listen(3000, function () {
console.log("Example app listening on port 3000");
});
当我访问不存在的网址 http://localhost:3000/xyz
时,我得到的标准页面显示 Cannot GET/xyz
,而不是我的自定义错误页面。为什么?
最佳答案
您使用的函数签名(err、req、res、next
)用于错误。例如。中间件调用 next(new Error('failed'))
。您需要的是一个常规中间件,它恰好是最后执行的中间件,这意味着您将其解释为 404(请参阅下面的答案)。
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/test-angular.html');
})
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.sendFile(__dirname + '/public/error.html');
});
//------------------
app.use(function(req, res, next) {
res.status(404);
res.sendFile(__dirname + '/public/error.html');
});
//------------------
var server = app.listen(3000, function () {
console.log("Example app listening on port 3000");
});
关于node.js - 使用express Node js无法拦截404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35101339/