node.js - 使用express Node js无法拦截404

标签 node.js express

这是我的代码:

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/

相关文章:

node.js - 错误状态 : 404 returned with PUT request using Node. js (express)、Angular 和 MongoDB

Node.js Sequelize 无法读取 nulll 的属性

node.js - 如何直接调用Connect中间件?

javascript - Express.js 从 MongoDB ID 创建 URL

node.js - 相当于 mongodb 中的 INET_ATON()

javascript - Node 的 q.fcall 返回一个空对象

node.js - 尝试在 Ubuntu 上安装 Node 时出错

node.js - 在node.js中我无法将变量传递给类的成员函数

node.js - DialogFlow 操作 - 谷歌 : Call an Intent from a current Intent

javascript - 服务器端未定义 renderProps/React/React-Router + Node/Express.js 的同构渲染