res.render("index", { name: "Alice" });We also used an object literal to define the content type for a Node project:
res.writeHead({"Content-Type", "text/html"});
JSON.stingify
JSON.parse
const s = `[{"x":5,"y":1},{"x":3,"y":2},{"x":0,"y":4}, {"x":1,"y":3},{"x":-1,"y":1}]`; const a = JSON.parse(s); var sum = 0; for(let i = 0; i <= 3; i++) { sum += a[i].x * a[i+1].y; } console.log(sum); // Answer: // Variable Trace Table: i sum product a[i].x a[i+1].y =====+=====+=======+======+======== 0 0 10 10 5 2 1 22 12 3 4 2 22 0 0 3 3 23 1 1 1 Output: 23
> npm init > npm i express ejsCreate data and views folders with files predictions.json, main.js, magic-8ball.ejs, and route-not-found.ejs using this structure:
-- Folder and file structure for Magic8Ball Example. data predictions.json views magic-8ball.ejs route-not-found.ejs main.jsHere are the source code files:
----------------------------------- // Magic8Ball Example // Source code file: main.js const express = require("express"); const fs = require("fs"); const app = express( ); const PORT = 3000; // Set View Engine to EJS app.set("view engine", "ejs"); // Array of 20 Magic 8-Ball Predictions var preds; fs.readFile("data/predictions.json", (err, data) => { if (err) { console.log("Error reading from predictions.json"); } else { preds = JSON.parse(data); } }); // Define /prediction route. app.get("/prediction", (req, res) => { // Pass the preds array to the EJS page. res.render("magic-8ball.ejs", { predictions: preds}); }); // If undefined route is entered, show route-not-found // page. app.get("*", (req, res) => { res.render("route-not-found.ejs"); }); // Start server for port 3000. app.listen(PORT, ( ) => { console.log(`Server listening on Port ${PORT}`); }); ----------------------------------- <!DOCTYPE html> <!-- Magic8Ball Example Source code file: views/magic-8ball.ejs --> <html lang="en"> <head> <meta charset="UTF-8"> <title>Magic 8-Ball Prediction</title> </head> <body> <!-- Choose Random Prediction --> <% var n = predictions.length; var randomIndex = Math.floor(Math.random( ) * n); var prediction = predictions[randomIndex]; %> <h1>Magic 8-Ball Prediction</h1> <!-- Display random prediction on EJS page. --> <p><%= prediction %></p> </body> </html> ----------------------------------- <!DOCTYPE html> <!-- Magic8Ball Prediction Source code file: views/route-not-found.ejs --> <html lang="en"> <head> <meta charset="UTF-8"> <title>Route Not Found</title> </head> <body> <h1>Route Not Found</h1> <p>Please check the route and try again.</p> </body> </html> -----------------------------------
> npm init > npm i express ejsCreate data and views folders with files specials.json, main.js, specials.ejs, and route-not-found.ejs using this structure:
-- Folder and file structure for Specials Example. data specials.json views specials.ejs route-not-found.ejs public css styles.css main.jsHere are the source code files:
----------------------------------- const express = require("express"); const fs = require("fs"); const app = express( ); // Define specialsArray as a global variable (outside // of any function to it can be used anywhere in the // script. var specialsArray; fs.readFile("data/specials.json", (err, data) => { if (err) { console.log("Error reading from specials.json."); } else { specialsArray = JSON.parse(data); } }); // Set up the static folder named public app.use(express.static("public")); // Set up method call to handle the // /specials route. app.get("/specials", (req, res) => { res.render("specials.ejs", {specials: specialsArray}); }); // Start the server. app.listen(3000, ( ) => { console.log("Server started."); }); ----------------------------------- <!DOCTYPE html> <!-- DisplaySite3 Example Source code file: views/specials.ejs --> <html lang="en"> <head> <meta charset="UTF-8"> <title>Specials Example</title> <link rel="stylesheet" href="/css/styles.css"> </head> <body> <h1>Specials Example</h1> <table> <% for(s of specials) { %> <tr> <td><%= s.city %></td> <td><%= s.length %></td> <td>$<%= s.price %></td> </tr> <% } %> </table> </body> </html> ----------------------------------- /* DisplaySite3 Example Source code file: public/css/styles.css */ body { font-family: arial; } table { border-collapse: collapse; } td { border-style: solid; border-width: 2px; } td, th { padding: 5px; } -----------------------------------
UrlParameter Example:
localhost:3000/items/1313 is the parameter.
// UrlParameter Example // Source code file: main.js const express = require("express"); const app = express( ); // Set up a get route with a parameter app.get("/items/:id", (q, r) => { var itemId = q.params.id; console.log(q.params); r.send(`<p>ID of catalog item: ${itemId}</p>`); }); app.get("*", (q, r) => { r.send("<p>Route not found.</p>"); }); app.listen(3000, ( ) => { console.log("Listening at port 3000"); });
GetQuery Example:
localhost:3000/person?name=Alice&gender=F&age=11
const express = require("express"); const app = express( ); app.get("/person", (q, r) => { console.log(q.query); var query = q.query; r.send(`<p>Name: ${query.name}<br> Gender: ${query.gender}<br> Age: ${query.age}</p>`); }); app.listen(3000, ( ) => { console.log("Listening on port 3000."); });