[Fixed] How to manage the redirection in express.js?


I know there are plenty of similar questions like my, but I couldn’t find any solution for my problem.

I think the issue is that am not getting the product.html and I assume that there is also a problem with the redirection to the product.html.


<!DOCTYPE html>
    <meta charset="utf-8" />
    <form id="product" action="/information" method="POST">
      <label for="product_id">Enter product ID: </label>
      <input id="product_id" name="product_id" type="text" required />
      <input type="submit" />


const express = require("express");

// load data
const products = require("./data.json");

const app = express();

// static files

// form middleware
app.use(express.urlencoded({ extended: true }));

app.post("/information", (req, res) => {
  // ES6 deconstruction syntax, get user input
  const { product_id } = req.body;

  // search product array
  const product = products.find((product) => product.Product_ID === product_id);
  if (product) res.json(product);
  else res.send("product not found");

// redirect all GET requests to product form
app.get("*", (req, res) => {

app.listen(8000,console.log(`App listening at http://localhost:8000`));

When I run the code like above, I get the following error: The page isn’t redirecting properly

(Cookies & Cache is deleted). I even tried another project with a node.js server and the localhost in Firefox worked.

When I command the redirection out, I get this error: Cannot GET /

When I use "/" instead of "*" in the redirections, this error appears: Cannot GET /product.html

I don’t understand why it doesn’t get the product.html and why the redirection doesn’t work right.


To render product.html for every endpoint, you can use sendFile rather than redirect, you will need to use path module, which is a core module to resolve the path to html file:

 const path = require('path');
 //your code
 app.get('*', (req, res)=> {
      //note that product.html file is in the same directory or you specify    
      //its relative path
      res.sendFile(path.resolve(__dirname, 'product.html'))

Leave a Reply

(*) Required, Your email will not be published