Handle 404 error with Express 4
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,
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.