Make 404 Page in Node.js Page not found

What is a 404 Page?

A 404 page means "Page Not Found". This shows up when a user tries to visit a page on your website that doesn't actually exist.


Why is 404 Page Important?

Without a 404 page:

  1. User sees a blank or error page.
  2. They may think your website is broken or not working.

With a 404 page:

  1. You can show a friendly message.
  2. Tell the user that the website is fine, but the page they requested doesn't exist.


Make a File for 404 Page

Create a new HTML file named 404.html inside the view folder.

You can use ChatGPT to generate a beautiful and simple 404 HTML template.


Use Function for 404 Page in Express

Express provides a special function app.use() — it's a multi-purpose middleware and is also used to handle 404 errors.


app.use((req, resp) => {
const absPath = path.resolve("view/404.html");
resp.status(404).sendFile(absPath);
});


Improvement: Make Common Absolute Path

To avoid repeating path.resolve() again and again, create a common absolute path for the whole folder (not individual files):'

const absPath = path.resolve("view");

Then use it like this:

app.use((req, resp) => {
resp.status(404).sendFile(absPath + "/404.html");
});