Welcome folks today in this blog post we will be serving different html
files based upon the query parameters in node.js and express. All the full source code of the application is shown below.
Get Started
In order to get started you need to make the node.js
project by using the below command as shown below
npm i express
And now you need to make the index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 |
const express = require('express') const fs = require('fs') const app = express() app.listen(5000,() => { console.log("App is listening on port 5000") }) |
As you can see we are starting the express
app at port 5000.
And now we need to write the get
request so that we can pass the query parameters as shown below
1 2 3 4 5 6 7 8 9 10 11 12 |
app.get('/:name',(req,res) => { console.log(req.params) if(req.params.name == "john"){ readAndServe("./john.html",res) } else if(req.params.name == "kane"){ readAndServe("./kane.html",res) } else{ readAndServe("./404.html",res) } }) |
As you can see in the above code we are getting the query parameter which is name
and then we can get access to this parameter using the req.params
and then we are comparing if it equals to john then we are showing the john.html
and else if it’s equal to kane
then we are showing the kane.html page and if name is different then we are showing the 404.html
page.
Now we need to serve the local
html file using the readAndServe()
method as shown below
1 2 3 4 5 |
let readAndServe = (path,res) => { fs.readFile(path,(err,data) => { res.end(data) }) } |
And now we need to define the three html
files as shown below
john.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>John Page</title> </head> <body> <h1>This is the John Page</h1> </body> </html> |
kane.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Kane Page</title> </head> <body> <h1>This is the Kane Page</h1> </body> </html> |
404.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>404 error page</title> </head> <body> <h1>This is the 404 Error page</h1> </body> </html> |
Now if you run the express
app as shown below
node index.js