Handle 404 Error Using Express 4

I am using Express 4 and I have about 50 html pages. I am trying to handle 404 errors but cannot figure out how to do this. I do not want to manually define all routers in node. Is there a way to dynamically redirect a 404 Jade template if the page does not exist?

I tried this code but did not 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;
    }
});
+4
source share
1 answer

This works 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 a query like this

http: // localhost: 3000 / sample

This is due to middleware.

UPDATE

The way to display html files without writing a get request is another middleware similar to this

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

"views" "public".

,

http://localhost:3000/index.html

.

+6

Source: https://habr.com/ru/post/1658615/


All Articles