Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle 404 error with Express 4

I am using Express 4 and I have about 50 html pages. I'm trying to handle 404 errors but can't figure out how. I don't want to manually define all the routers within node. Is there a way to dynamically redirect to a 404 Jade template if a page doesn't exist?

I tried this code but didn't work:

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;
    }
});
like image 267
AlexisP Avatar asked Oct 23 '16 14:10

AlexisP


People also ask

How does express JS handle 404?

All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response: app. use((req, res, next) => { res. status(404).

How do you fix the 404 error?

The simplest and easiest way to fix your 404 error code is to redirect the page to another one. You can perform this task using a 301 redirect. What's 301, you may ask? It's a redirect response code that signals a browser that the content has been transferred to another URL.

Why am I getting an error 404 message?

A 404 error indicates that the webpage you're trying to reach can't be found. You might see a 404 error because of a problem with the website, because the page was moved or deleted, or because you typed the URL wrong.


1 Answers

This is working for me:

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!');
});

Folder structure,

enter image description here

Now when we issue the request like this

http://localhost:3000/sample

This has been handled by the middleware.

UPDATE

The way to show the html files without writing the get request is just another middleware like this

app.use(express.static('public'));
app.use(express.static('views'));

Add the 'views' middleware exactly after the 'public'.

Now if we give

http://localhost:3000/index.html

The page is rendered.

like image 94
shanmugharaj Avatar answered Sep 16 '22 22:09

shanmugharaj