How to send different HTML files based on query parameters in Node.js ?
Last Updated :
22 Apr, 2021
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" );
function readAndServe(path, res) {
fs.readFile(path, function (err, data) {
res.end(data);
})
}
app.get( '/:id' , function (req, res) {
console.log(req.params);
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...