Search code examples
node.jsexpresshttp-status-code-404backend

Add a failure page when a 404 error is found in Express


I made a Dictionary using an API that works perfectly fine until a random string is entered which crashes the app giving a 404 error. I want to add a failure page instead which will in turn have a button that on clicking would redirect me to the home page.

const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
const request = require("request");
// const routes = require("routes");

const app = express();
app.use(bodyParser.urlencoded({extended: true}));
// app.use(routes);

app.get("/", function(req, res) {
  res.sendFile(__dirname + "/search.html");
})

app.post("/", function(req, res) {
  const word = req.body.word;
  const code = req.body.code;
  console.log(code);
  const url = "https://api.dictionaryapi.dev/api/v2/entries/" + code + "/" + word;

  https.get(url, function(response) {

    response.on("data", function(data) {
      if(response.statusCode >= 404){
        res.sendFile(__dirname + "/failure.html");
      }
      console.log(response.statusCode);
      const meaning = JSON.parse(data);
      const definition = meaning[0].meanings[0].definitions[0].definition

      res.send("<h1>" + definition + "</h1>");
      //  console.log(definition);

    })
  })
})

app.post("/failure", function(req, res) {
  res.redirect("/");
})

// app.use(function(req, res, next){
//   res.send("Hiiiiiiiiii");
// })

app.listen(process.env.PORT || 3000, function() {
  console.log("Server running properly");
})

I am new to Express and have tried whatever I could find on the Internet so far, yet none worked.

The failure page I am trying to add looks like this:

enter image description here

Can anyone please help?


Solution

  • Simply listen for the "*" path at the bottom of your router. The "*" means anything else, so if the page is not found it'll provide a fallback instead of constantly searching.

    Example:

    app.all('*', function(req, res) {
        // Do something
    });
    

    Full example:

    const express = require("express");
    const bodyParser = require("body-parser");
    const https = require("https");
    const request = require("request");
    
    const app = express();
    app.use(bodyParser.urlencoded({ extended: true }));
    
    app.get("/", function(req, res) {
      res.sendFile(__dirname + "/search.html");
    })
    
    app.post("/", function(req, res) {
      const word = req.body.word;
      const code = req.body.code;
      console.log(code);
      const url = "https://api.dictionaryapi.dev/api/v2/entries/" + code + "/" + word;
    
      https.get(url, function(response) {
    
        response.on("data", function(data) {
          if(response.statusCode >= 404){
            res.sendFile(__dirname + "/failure.html");
          }
          console.log(response.statusCode);
          const meaning = JSON.parse(data);
          const definition = meaning[0].meanings[0].definitions[0].definition
    
          res.send("<h1>" + definition + "</h1>");
          //  console.log(definition);
    
        })
      })
    })
    
    app.post("/failure", function(req, res) {
      res.redirect("/");
    });
    
    app.all('*', function(req, res) {
        // Do something
    });
    
    app.listen(process.env.PORT || 3000, function() {
      console.log("Server running properly");
    })