forked from freeCodeCamp/boilerplate-express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyApp.js
88 lines (54 loc) · 2.25 KB
/
myApp.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
var express = require('express');
var app = express();
// --> 7) Mount the Logger middleware here
app.use('/', (req, res, next) => {
console.log(req.method, req.path, '-', req.ip);
next();
})
// --> 11) Mount the body-parser middleware here
/** Let’s serve our first string! In Express, routes takes the following structure: app.METHOD(PATH, HANDLER).
* METHOD is an http method in lowercase. PATH is a relative path on the server (it can be a string, or even a regular expression).
* HANDLER is a function that Express calls when the route is matched.
Handlers take the form function(req, res) {...}, where req is the request object, and res is the response object. For example, the handler */
console.log('server runs on port 3000')
app.get('/', (req, res) => res.send("Hello Express"))
/** 3) Serve an HTML file
* to serve file we use sendFile method
* */
app.get('/form', (req, res) => res.sendFile( __dirname + '/views/index.html'))
/** 4) Serve static assets */
app.use(express.static(__dirname + '/public/'))
/** 5) serve JSON on a specific route */
//app.get('/json', (req, res) => res.json({"message": "Hello json"}))
/** 6) Use the .env file to configure the app */
app.get('/json', (req, res) => {
let message = 'Hello json';
if(process.env.MESSAGE_STYLE === 'uppercase') {
message = message.toUpperCase()
}
return res.json({"message": message})
})
/** 7) Root-level Middleware - A logger */
// place it before all the routes !
/** 8) Chaining middleware. A Time server */
app.get('/now', (req, res, next) => {
req.time = new Date().toString()
console.log(req.time);
next();
}, (req, res) => res.json({"time": req.time}))
/** 9) Get input from client - Route parameters */
app.get('/:word/echo', (req, res) => {
let word = req.params.word
res.json({"echo": word})
})
/** 10) Get input from client - Query parameters */
// /name?first=<firstname>&last=<lastname>
app.route("/name").get((req, res) => {
res.json({ "name": req.query.first + ' ' + req.query.last })
});
/** 11) Get ready for POST Requests - the `body-parser` */
// place it before all the routes !
/** 12) Get data form POST */
app.listen(process.env.PORT || 3000 );
//---------- DO NOT EDIT BELOW THIS LINE --------------------
module.exports = app;