So I create a file called 404.html
and used this code in the index.js
file:
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const port = process.env.PORT || process.env.port || 3000;
app.use(express.static(__dirname + "/public"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("*", (req, res) => {
res.sendFile(__dirname + "/404.html");
});
server.listen(port, () => {
console.log("Server listening on port:", port);
});
But when I visit a url that doesn’t exist, for example, https://node-app.qwertyqwerty54.repl.co/about
, the 404 page doesn’t show up, instead this shows up:
I’ve found the fix to change this line of code:
res.sendFile(__dirname + "/404.html");
to this:
res.sendFile(__dirname + "/public/404.html");
But my question is, why doesn’t the first version work?
It works for the index.html
page, so why not the 404 page?
Almost forgor to include Repl link XD
https://replit.com/@QwertyQwerty54/node-app