Last active
June 19, 2021 08:13
-
-
Save primaryobjects/0beed74756074d3df6e3 to your computer and use it in GitHub Desktop.
Redirect 404 errors to a static web page in node.js Express.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
// In your app.js, include a route handler for all other routes (*) to go to error404. | |
// app.get('*', error.error404); | |
exports.error404 = function(req, res) { | |
if (req.accepts('html')) { | |
// Respond with html page. | |
fs.readFile(__dirname + '/../../public/404/index.html', 'utf-8', function(err, page) { | |
res.writeHead(404, {'Content-Type': 'text/html'}); | |
res.write(page); | |
res.end(); | |
}); | |
} | |
else if (req.accepts('json')) { | |
// Respond with json. | |
res.status(404).send({ error: 'Not found' }); | |
} | |
else { | |
// Default to plain-text. send() | |
res.status(404).type('txt').send('Not found'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, this was very helpful