Extending to Multiple Pages

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 239:- Extending to Multiple Pages

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.

28. Node.js Writing - Our First Server

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

I am not able to access videos from second class and further. I have already completed first class

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?