-
Notifications
You must be signed in to change notification settings - Fork 0
/
fullExample.js
89 lines (72 loc) · 2.28 KB
/
fullExample.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var express = require("express");
var bodyParser = require("body-parser"); // it's should be in the starter json file otherwise install
var app = express();
const base = __dirname;
// (7) Implement a Root-Level Request Logger Middleware
app.use(function (req, res, next) {
console.log(`${req.method} ${req.path} - ${req.ip}`);
next();
});
// (11) Use body-parser to Parse POST Requests
app.use(bodyParser.urlencoded({ extended: false }));
// (1) Meet the node console.
console.log("Hello World");
// (2) Start a Working Express Server
app.get("/", function (req, res) {
res.send("Hello Express");
});
// (4) Serve Static Assets
// ex2 should be replaced with 3,4 from now
app.use("/public", express.static(base + "/public"));
// (3) Serve an HTML file
app.get("/", function (req, res) {
const htmlPath = base + "/views/index.html";
res.sendFile(htmlPath);
});
// (5) Serve JSON on a Specific Route
app.get("/json", function (req, res) {
const msg = { message: "Hello json" };
res.json(msg);
});
// (6) Use the .env File
// ex5 should be replaced with 6 from now
const mySecret = process.env["MESSAGE_STYLE"]; // =uppercase (in your .env or Replit/Secrets)
app.get("/json", function (req, res) {
const msg = "Hello json";
process.env.MESSAGE_STYLE === "uppercase"
? res.json({ message: msg.toUpperCase() })
: res.json({ message: msg });
});
// (8) Chain Middleware to Create a Time Server
app.get(
"/now",
function (req, res, next) {
req.time = new Date().toString();
next();
},
function (req, res) {
res.json({ time: req.time });
}
);
// (9) Get Route Parameter Input from the Client
app.get("/:word/echo", function (req, res) {
res.json({ echo: req.params.word });
});
// (10) Get Query Parameter Input from the Client
app
.get("/name", function (req, res) {
const first = req.query.first;
const last = req.query.last;
const data = { name: `${first} ${last}` };
res.send(data);
}) // (12) Get Data from POST Requests
.post("/name", function (req, res) {
const postData = req.body.first + " " + req.body.last;
res.json({ name: postData });
});
/*
===========================================================
DO NOT EDIT BELOW THIS LINE
===========================================================
*/
module.exports = app;