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

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

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

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support