Goal: Create a test website and an Express server to display the website pages on localhost. This tutorial will use the response method render, not sendFile.
Your site will display pages for these sample 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 sample routes are index.html, contact-us.html, specials.html, and route-not-found.html. For this tutorial these HTML files must be placed in the views folder, which is a subfolder of the project folder. In addition, each of the .html file extension for each of the HTML files must be replaced by the file extension .ejs, which means embedded JavaScript. You can use the HTML files from Tutorial4a, but change the file extension of each to .ejs. We will see how to actually insert JavaScript statements into an Embedded JavaScript file file when we complete Tutorial 5 and Project 3.
> npm i express
> npm i ejs
const app = express( );
app.use(express.static("public"));
app.set("view engine", "ejs");
app.get("/", (req, res) => { res.render("index"); });res.render assumes that the file to render is in the views folder, and that its file extension is .ejs.
app.get("*", (req, res) => { res.render("route-not-found")); });
const PORT = 3000; app.listen(PORT, ( ) => { console.log("Server started; " + `listening on port ${PORT}.`); });Notice that, in addition to the port argument, the Express app object also accepts a callback function that is called when the app starts listening.