Verified Commit 3a27c923 authored by Aral Balkan's avatar Aral Balkan
Browse files

Return proper 404s without sacrificing custom 404 page simplicity

parent 7486f5bd
......@@ -95,15 +95,22 @@ class WebServer {
const app = express()
app.use(helmet()) // Express.js security with HTTP headers.
app.use(morgan('tiny')) // Logging.
// 404 (Not Found) support.
app.use((request, response, next) => {
// If there is a custom 404 page, serve that. The template variable
// If there is a custom 404 path, serve that. The template variable
// THE_PATH, if present on the page, will be replaced with the current
// request path before it is returned.
if (hasCustom404) {
// Enable basic template support for including the missing path.
const custom404WithPath = custom404.replace('THE_PATH', request.path)
// Enable relative links to work in custom error pages.
const custom404WithPathAndBase = custom404WithPath.replace('<head>', '<head>\n\t<base href="/404/">')
} else {
// Send default 404 page.
response.status(404).send(`<!doctype html><html lang="en" style="font-family: sans-serif; background-color: #eae7e1"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Error 404: Not found</title></head><body style="display: grid; align-items: center; justify-content: center; height: 100vh; vertical-align: top; margin: 0;"><main><h1 style="font-size: 16vw; color: black; text-align:center; line-height: 0.25">4🤭4</h1><p style="font-size: 4vw; text-align: center; padding-left: 2vw; padding-right: 2vw;"><span>Could not find</span> <span style="color: grey;">${request.path}</span></p></main></body></html>`)
......@@ -53,6 +53,18 @@ test('serve method', t => {
t.equal(response.statusCode, 200, 'request succeeds')
t.equal(response.body, indexHTML, 'index loads')
// let notFoundResponse
// try {
// response404 = await secureGet('https://localhost/this-page-does-not-exist')
// } catch (error) {
// console.log(error)
// process.exit(1)
// }
// t.equal(response.statusCode, 404, 'response is 404')
// console.log(response.body)
......@@ -8,13 +8,15 @@
html {font-family: sans-serif; background-color: #eae7e1}
body {display: grid; align-items: center; justify-content: center; height: 100vh; vertical-align: top; margin: 0;}
main {padding-left: 2vw; padding-right: 2vw;}
p {text-align: center;}
<!-- Note: All your URLs in custom error files must be -->
<img src="hmm-monster.svg" alt="Green monster, thinking.">
<p><strong>Sorry, I can’t find </strong> <span id='that-page'>that page.</span><script>document.getElementById('that-page').innerText = (new URLSearchParams('not-found'))</script></p>
<p><strong>Sorry, I can’t find</strong> THE_PATH</p>
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment