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)
})
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" ],
]
Step 2:
Create a forEach loop
pages.forEach(pages =>{
// GET method route
app.get(pages[0], (req, res) => {
res.sendFile(__dirname + "/" + pages[1])
})
})
Step 3:
Run the complete code :
usign node js :
node ./file_name.js
usign nodemon : you need to install nodemon
// installing commande
npm install -g nodemon
// running commonde
nodemon ./file_name.js
Top comments (1)
Why are you using express? For this usecase you don't even need express or node. A simple Nginx would be enough.