Mister_L
Mister_L

Reputation: 2611

Can't intercept 404 with express node js

This is my code:

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");
});

When I access the url http://localhost:3000/xyz, which does not exist, I get the standard page saying Cannot GET /xyz, instead of my custom error page. Why?

Upvotes: 2

Views: 675

Answers (2)

Prinzhorn
Prinzhorn

Reputation: 22508

The function signature you're using (err, req, res, next) is for errors. E.g. a middleware calls next(new Error('failed')). What you need is a regular middleware which simply happens to be the last one that is executed, which means you interpret it as 404 (see answer below).

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");
});

Upvotes: 2

Piyush Sagar
Piyush Sagar

Reputation: 3129

Node usually starts matching endpoints from top to bottom.

So first write down all the endpoints of your app, then write an endpoint like below at the end which will be executed when none of your defined endpoints match.

 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
 })

Your code should look like this :

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");
});

Upvotes: 2

Related Questions