Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active June 19, 2021 08:13
Show Gist options
  • Save primaryobjects/0beed74756074d3df6e3 to your computer and use it in GitHub Desktop.
Save primaryobjects/0beed74756074d3df6e3 to your computer and use it in GitHub Desktop.
Redirect 404 errors to a static web page in node.js Express.
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');
}
};
@UnrulyJuli3
Copy link

Thanks, this was very helpful

@Craftit7
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment