无法使用快速节点js拦截404

时间:2016-01-30 11:42:16

标签: 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标准页面,而不是我的自定义错误页面。为什么?

2 个答案:

答案 0 :(得分:1)

您正在使用的功能签名(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");
});

答案 1 :(得分:0)

节点通常从从上到下开始匹配端点。

因此,首先记下应用程序的所有端点,然后在最后编写一个端点,如下所示,当您定义的端点都不匹配时,将执行该端点。

 app.get('/path1', handler1);
 app.get('/path2', handler2);
 app.get('/path3', handler3);
 app.get('/*',function (req, res) {
  //This block will executed when user tries to access endpoint other than /path1,/path2,/path3
  // Handle error here
 })

您的代码应如下所示:

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.get('/*',function (req, res) {  //If any of your defined endpoints doesn't match, this block will be executed. 
   res.status(404);
   res.sendFile(__dirname + '/public/error.html');
});

var server = app.listen(3000, function () {
   console.log("Example app listening on port 3000");
});