DEV Community

Yuba El Oualidi
Yuba El Oualidi

Posted on • Updated on

Best Express JS Routing For Multiple WebPages

We learn in this tutorial, how to make the best express js routing code.

This a simple express js code example:

const express = require('express')
const app = express()

// GET method route
app.get('/', (req, res) => {
  res.send('GET request')
})

// POST method route
app.post('/', (req, res) => {
  res.send('POST request)
})
Enter fullscreen mode Exit fullscreen mode

This method is good, if you have just one webpage, but is not good for multiple pages, because you will need to repeat the code more than once.

So, you can use the Foreach for example to solve this problem:

Solve Problem Steps:

Step 1:

Create the Array variable like this :

const pages = [
   ["/"        , "index.html"  ],
   ["/contact" , "contact.html"],
   ["*"        , "404.html"    ],
]
Enter fullscreen mode Exit fullscreen mode

Step 2:

Create a forEach loop

pages.forEach(pages =>{
  // GET method route
  app.get(pages[0], (req, res) => {
    res.sendFile(__dirname + "/" + pages[1])
  })
})

Enter fullscreen mode Exit fullscreen mode

Step 3:

Run the complete code :

usign node js :

node ./file_name.js
Enter fullscreen mode Exit fullscreen mode

usign nodemon : you need to install nodemon

// installing commande
npm install -g nodemon

// running commonde
nodemon ./file_name.js
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
giovapanasiti profile image
Giovanni Panasiti

Why are you using express? For this usecase you don't even need express or node. A simple Nginx would be enough.