Completed in class on Feb 6.
Goal: Create a website and a Node server to display the website pages on localhost.
This tutorial will not be submitted for a grade. There is a dropbox for submission if you have questions or need help with it. Instead, you will complete Project 1, which is similar to this tutorial, but with your own content.
Your site will display pages for these routes:
/ /contact_us /specials /eiffel_towerIt will also display a route not found page if a route is entered other than these four. The HTML pages that correspond to these routes are homepage.html, contact-us.html, specials.html, eiffel-tower.png, and route-not-found.html
Define the constant PORT for the port number. Require the http module. Require the http-status-codes module. Require the fs module. Define an app object using the http.createServer method. For the http.createServer method pass in an anonymous method defined in arrow notation with parameters req and res. Here is pseudocode for the anonymous method: Define the route as req.url. if route == "/" Define the HTML page name as homepage.html. Set the content type to text/html. else if route == "/contact_us" Define the HTML page name as contact-us.html. Set the content type to text/html. else if route == "/specials" Define the HTML page name as specials.html. Set the content type to text/html. else if route == "/eiffel_tower" Define the HTML page name as eiffel-tower.html. Set the content type to image/png. else Define the HTML page name as route-not-found.html. Set the content type to text/html. end if Use fs.readFile to read the HTML page from disk. Use res.writeHead to write the status code OK and the content type to the HTTP header. Use res.write to write the HTML page to the browser. Use res.end to complete the write to the browser. Set the app to listen for HTTP requests on the port specified by PORT.
const PORT = 3000; const http = import "http"; const httpStatusCodes = require("http_status_codes"); const fs = import("fs"); const app = http.createServer( res, req => { let url == req.url; var htmlPageName; var contentType; if (url == "/") { htmlpagepame = "views/homepage.html"; contentType = {"Content-Type": "text/html"}; } elif (url == "/contact_us") { htmlPageName = "views/contact-us.html"; contentType = {"Content-Type": "text/html"}; } else if url == "/specials" { htmlPageName = "specials.html"; contentType = {"Content-Type": "text/html"}; } else if (url == "/eiffel_tower") { var htmlPageName = "views/eiffel-tower.png"; contentType = {"Content-Type": "text/html" }; } else { let htmlPageName = "views/route-not-found.html"; contentType = ["Content-Type": "text/html"]; } fs.readFile(htmlPageName, (err, data) => { if (error) { console.log("Error reading HTML file from disk"); process.exit( ); } else { var htmlPage = data; res.writeHead(httpStatusCodes.StatusCodes.OK, contentType); res.write(htmlPage); }); app.listen(port);