Open In App

How to send different HTML files based on query parameters in Node.js ?

Last Updated : 22 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The following approach covers how to send different HTML files based on the query parameters in Node.js

Approach: The task can be easily fulfilled by receiving the query parameters and map different HTML files with the respective parameters.

Step 1: Create your project folder and install the express module using the following command:

npm install express

Step 2: Create a main.js file in the root directory of your project and write down the following code in it.

main.js




var express = require('express');
var app = express();
const fs = require("fs");
  
// Helper function to read and serve html files 
// according to the requested paths 
function readAndServe(path, res) {
    fs.readFile(path, function (err, data) {
        res.end(data);
    })
}
  
// Setting get request path to receive id as query parameter 
app.get('/:id', function (req, res) {
    console.log(req.params);
  
    // Mapping different id's with respective html files
    if (req.params.id == "id1")
        readAndServe("./id1.html", res);
    else if (req.params.id == "id2")
        readAndServe("./id2.html", res);
    else {
        res.end("Invalid request");
    }
});
  
app.listen(8080, () => { console.log("Server Listening on Port 8080") });


Step 3: Create id1.html and id2.html files in the root directory of your project as shown below.

id1.html




<!DOCTYPE HTML>
<html>
    <head>
        <title>Id 1</title>
    </head>
    <body>
        <h1>Requested Id = 1</h1>
    </body>
</html>


id2.html




<!DOCTYPE HTML>
<html>
    <head>
        <title>Id 2</title>
    </head>
    <body>
        <h1>Requested Id = 2</h1>
    </body>
</html>


Step 4: Run the server using the following command from the root directory of the project:

node main.js

Output:

  • Now open your browser and go to http://localhost:8080/id1, you will see the following output when id1 is passed as a query parameter.

  • Now go to http://localhost:8080/id2, you will see the following output when id2 is passed as a query parameter.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads