Making It Functional
Learn how to serve multiple pages with the HTTP server.
We'll cover the following
Creating the page for a restaurant
Let’s create a restaurant menu page where we can add food to our cart. Let’s also modify our main page so that we are shown the restaurant page when we click on a food type.
const http = require("http"); const fs = require("fs"); const hostname = "0.0.0.0"; const port = 3500; const homePage = fs.readFileSync("main.html"); const aboutPage = fs.readFileSync("about.html"); const menuPage = fs.readFileSync("menu.html"); const css = fs.readFileSync("styles.css"); const server = http.createServer((req, res) => { res.statusCode = 200; if (req.url == "/") { res.statusCode = 200; res.setHeader("Content-Type", "text/html"); res.write(homePage); } else if (req.url == "/about") { res.statusCode = 200; res.setHeader("Content-Type", "text/html"); res.write(aboutPage); } else if (req.url == "/menu") { res.statusCode = 200; res.setHeader("Content-Type", "text/html"); res.write(menuPage); } else if (req.url == "/styles.css") { res.statusCode = 200; res.setHeader("Content-Type", "text/css"); res.write(css); } else if (req.url.match(/images/g)) { try { res.statusCode = 200; res.setHeader("Content-Type", "image/jpeg"); imgLoc = req.url.replace("/", "../"); image = fs.readFileSync(imgLoc); res.end(image); } catch { res.statusCode = 404; res.write("404"); console.log(req.url); } } else { res.statusCode = 404; res.write("404"); console.log(req.url); } res.end(); }); server.listen(port, hostname, () => { console.log("Server is now running"); });
The menu page
The menu page is a static webpage with a few food items listed neatly. If we had to change our prices or add a new food item, we would have to edit this page. Most of the layout is similar to the main page, and you can navigate the website using the hamburger menu. All food outlets use the same menu for now.
The shopping cart
While most of the code is written in HTML, we used JavaScript to implement the shopping cart. Check out the menu.html file to learn more about that. The cart adds up the cost of all the items and uses an alert()
to thank the customer once they hit purchase. Nothing happens, though.
More on Node.js
Serving static pages without using packages can be a challenge if you are just starting with Node.js. Thanks to packages, we rarely have to interact with low-level APIs such as http
and net
when creating websites. Nowadays, dynamic web pages often use a database to fetch the latest information. That information is then displayed using front-end frameworks that allow us to make beautiful and lively websites. We can use one of the technology stacks discussed in this lesson or build a much more robust website.
Get hands-on with 1300+ tech skills courses.