If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To extend our server to serve multiple pages, we need to create multiple routes. We can use the URL to determine which route should be used.
Let's say we have two pages, home
and about
. We can create two separate HTML files for each of them, and our server should be able to serve them based on the URL requested.
We can define two routes, one for each page. Here's an example of how we can do it:
jsCopy code
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
const { url } = req;
let filePath = './views/';
switch(url) {
case '/':
filePath += 'home.html';
break;
case '/about':
filePath += 'about.html';
break;
default:
filePath += '404.html';
break;
}
fs.readFile(filePath, (err, data) => {
if (err) {
console.error(err);
res.writeHead(500, { 'Content-Type': 'text/html' });
res.end('<h1>Server Error</h1>');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
});
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});
Here, we first extract the URL from the request object. Then we use a switch
statement to determine which file should be served based on the URL.
We also have a default case which serves a 404.html
file if the requested URL doesn't match any of our defined routes.
Finally, we read the file using fs.readFile
and serve it to the client using the response object.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.