Skip to content

Commit 1aaa6e4

Browse files
[mabel] Add exercises to express chapters
1 parent 3d06d2b commit 1aaa6e4

File tree

7 files changed

+203
-44
lines changed

7 files changed

+203
-44
lines changed
Lines changed: 8 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
# Express.js basics
22

3-
Express.js framework is built on top of Node.js for simpler web server development. Express.js comes with parsing, security, user sessions, error handling etc, that are not handled by Node.js
3+
- Installing Express.js
4+
- Features of Express.js
5+
- Your first Express.js app
6+
- Start Express.js server
7+
8+
Express.js framework is built on top of Node.js for simpler web server development. Express.js comes with parsing, security, user sessions, error handling etc, that are not handled by Node.js. If you use Node.js, you will have to constantly reimplement all these.
9+
10+
It is minimalistic, does not restrict you to any design patterns or file structure, and often requires you to install more packages to add functionality.
411

512
## Installing Express.js
613

@@ -32,37 +39,3 @@ const server = app.listen(PORT, () => {
3239
console.log(`Server started on port ${PORT}...`);
3340
});
3441
```
35-
36-
## Testing the server
37-
38-
### cURL
39-
40-
Client URL
41-
cURL is by default already installed in Mac OS. For Windows, you can download cURL separately.
42-
You can send different HTTP requests.
43-
44-
For example, let's send a POST request to https://localhost:3000/users with a JSON message body.
45-
46-
```sh
47-
curl --request POST \
48-
--url https://localhost:3000/users \
49-
--header 'content-type: application/json' \
50-
--data '{
51-
"username": "babel",
52-
}'
53-
```
54-
55-
Alternatives to the flags:
56-
57-
```sh
58-
curl -X POST \
59-
http://localhost:3000/users \
60-
-H 'content-type: application/json' \
61-
-d '{
62-
"username": "babel"
63-
}'
64-
```
65-
66-
### API testing tool
67-
68-
Instead of cURL, you can use an API testing tool like Postman or Insomnia. You can even save your requests and organise them into folders. Using those tools, compose a request to "http://localhost:port/" where `port` is the port that your server is listening to.

docs/backend-web-development/express-param-processing.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,12 @@ Quoting the Express.js docs on `app.param`:
6565
> Param callback functions are local to the router on which they are defined. They are not inherited by mounted apps or routers. Hence, param callbacks defined on app will be triggered only by route parameters defined on app routes.
6666
6767
To define the parameter callbacks on a router instead, use `router.param`.
68+
69+
## Exercises
70+
71+
Refactor the previous songs route to use `app.param` for the `id` parameter.
72+
Find the song of that particular id and put the song in the request object.
73+
74+
```js
75+
req.song = song;
76+
```

docs/backend-web-development/express-parsing-request-body.md

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Express.js parsing request body
22

3-
One of the very important middlewares is the one for parsing request body. It is built-in into Express.js.
3+
One of the very important middlewares is the one for parsing request body. It is built-in into Express.js. This is often forgotten and the cause of bugs.
44

55
Note that it used to be a seperate middleware called body-parser but it has been re-added into Express.js as a built-in middleware.
66

@@ -24,6 +24,8 @@ typeof express.json(); // 'function'
2424

2525
The request body of any request will be parsed by the middleware and placed in `req.body` before it is passed to the handler functions.
2626

27+
It is important to `app.use` the json parsing middleware **before** the handler functions. The order of adding middleware matters.
28+
2729
```js
2830
app.post("/users", (req, res) => {
2931
const userName = req.body.username;
@@ -50,3 +52,89 @@ app.use(express.urlencoded({ extended: false }));
5052
```
5153

5254
Read https://codewithhugo.com/parse-express-json-form-body/ for more information.
55+
56+
## Exercises
57+
58+
Add more API endpoints to the previous songs API that we had:
59+
60+
Add middleware for parsing JSON request body.
61+
62+
1. Route: POST /songs
63+
HTTP Response status code: 201
64+
65+
Add a new song with id, and return new song
66+
67+
JSON to include in the POST message body:
68+
69+
```json
70+
{
71+
"name": "someSongName",
72+
"artist": "someSongArtist"
73+
}
74+
```
75+
76+
Expected response:
77+
78+
```json
79+
{
80+
"id": 1,
81+
"name": "someSongName",
82+
"artist": "someSongArtist"
83+
}
84+
```
85+
86+
2. Route: GET /songs/:id
87+
HTTP Response status code: 200
88+
89+
Return a song with id using route parameters.
90+
91+
if route path is /songs/1, expected response is:
92+
93+
```json
94+
{
95+
"id": 1,
96+
"name": "someSongName",
97+
"artist": "someSongArtist"
98+
}
99+
```
100+
101+
3. Route: PUT /songs/:id
102+
HTTP Response status code: 200
103+
104+
Replace a song with id, and return modified song
105+
106+
JSON to include in the PUT message body:
107+
108+
```json
109+
{
110+
"name": "newSongName",
111+
"artist": "newSongArtist"
112+
}
113+
```
114+
115+
If the route path is /songs/1:
116+
117+
Expected response:
118+
119+
```json
120+
{
121+
"id": 1,
122+
"name": "newSongName",
123+
"artist": "newSongArtist"
124+
}
125+
```
126+
127+
4. Route: DELETE /songs/:id
128+
HTTP Response status code: 200
129+
130+
delete a song with id, and return deleted song
131+
132+
if route path is /songs/1, expected response is:
133+
134+
```json
135+
{
136+
"id": 1,
137+
"name": "someSongName",
138+
"artist": "someSongArtist"
139+
}
140+
```

docs/backend-web-development/express-responses.md

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Express.js responses
22

3+
- Ending response with res.end()
4+
- Sending back response with res.send() and res.json()
5+
- Writing to res.write() and comparing to res.send()
6+
- Setting status code of response
7+
38
The handler function or middleware function usually needs to call a method on the response object (res) to modify and send back a response.
49

510
## Ending a response
@@ -55,7 +60,7 @@ Read [this blog at Fullstacktraining](https://blog.fullstacktraining.com/res-jso
5560

5661
## Writing parts of response body
5762

58-
In the multiple handler functions routing example, we used `res.write()` to update the response before sending the response back to the client.
63+
In the multiple handler functions routing example, we used `res.write()` to update the response before sending the response back to the client. Normally, you will not need to use this.
5964

6065
```js
6166
res.write("Here is a list of students:\n");
@@ -107,3 +112,37 @@ res.sendStatus(500);
107112
```
108113

109114
See [Express.js api docs](https://expressjs.com/en/api.html#res.sendStatus) for more info.
115+
116+
## Should we implement many status codes?
117+
118+
No. The more status codes your API deals with, the more status codes you have to maintain. Your clients (possibly your frontend) will also have to maintain more code to react accordingly to these status codes. Use the status codes only as needed.
119+
120+
## Exercises
121+
122+
Implement an API with the following endpoint:
123+
124+
1. Route: GET /songs
125+
HTTP Response status code: 200
126+
127+
Expected response:
128+
129+
if empty:
130+
131+
```json
132+
[]
133+
```
134+
135+
if not empty, we will get an array of song objects in JSON.
136+
137+
```json
138+
[
139+
{
140+
"name": "someSongName",
141+
"artist": "someSongArtist"
142+
},
143+
{
144+
"name": "anotherSongName",
145+
"artist": "anotherArtist"
146+
}
147+
]
148+
```

docs/backend-web-development/express-routing.md

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# Express.js routing
22

3+
- What is routing
4+
- Request and response methods and objects
5+
- Route paths
6+
- Route parameters
7+
- Route querystrings
8+
- Multiple handler functions
9+
310
## What is routing?
411

512
Routing is a way to map requests to specific handlers depending on their URI and HTTP verb.
@@ -49,7 +56,7 @@ app.post("/", (req, res) => {
4956
});
5057
```
5158

52-
The handler function (callback function) is called when a GET request is sent by the browser to the root `/`. In the handler function, "Welcome to my homepage" is sent as the response.
59+
The handler function (callback function) is called when a GET or POST request is sent by the browser to the root `/`. In the handler function for GET request, "Welcome to my homepage" is sent as the response.
5360

5461
Express.js will call the handler function with two parameters. The first parameter is the request object and the second parameter is the response object.
5562

@@ -141,12 +148,13 @@ app.get(/.*fly$/, function (req, res) {
141148

142149
We can grab data from the route using route parameters. Route parameters are named segments of the URL used to capture values at their specified position.
143150

151+
The parameters are stored in `req.params`.
152+
144153
GET a specific book with ID:
145154

146155
```js
147156
app.get("/books/:bookId", (req, res) => {
148157
res.send(`You requested information on book ${req.params.bookId}`);
149-
// NOTE: the above line poses a security issue, we should always treat any user input as unsafe (see XSS attack)
150158
});
151159
```
152160

@@ -190,6 +198,8 @@ Refer to the script: [Express.js playground: query_parameter_example](https://gi
190198

191199
We can use querystrings to filter data, provide information to a page or even alter the action of a page. This is typically used with a GET request.
192200

201+
The queries are stored in `req.query`.
202+
193203
Considering that we have the following data:
194204

195205
```js
@@ -249,8 +259,6 @@ req.query: { "color": "red", "type": "FRUIT" }
249259

250260
```js
251261
app.get("/food", (req, res) => {
252-
//console.log(req.query);
253-
254262
const results = data
255263
// Using if statements
256264
.filter((item) => {

docs/backend-web-development/express-simple-server.md

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,6 @@ const server = app.listen(PORT, () => {
2828
});
2929
```
3030

31-
Use an API testing tool like Postman to test the route you just created.
32-
3331
### Other request methods
3432

3533
When making a POST, PUT or DELETE request at the root URL `/`, the server should send a response.
@@ -47,3 +45,45 @@ app.delete("/", (req, res) => {
4745
res.send(`Hello, i got a ${req.method} request`);
4846
});
4947
```
48+
49+
## Testing the server
50+
51+
### cURL
52+
53+
Client URL
54+
cURL is by default already installed in Mac OS. For Windows, you can download cURL separately.
55+
You can send different HTTP requests.
56+
57+
For example, let's send a POST request to https://localhost:3000/ with a JSON message body.
58+
59+
```sh
60+
curl --request POST \
61+
--url https://localhost:3000/ \
62+
--header 'content-type: application/json' \
63+
--data '{
64+
"username": "babel",
65+
}'
66+
```
67+
68+
Alternatives to the flags:
69+
70+
```sh
71+
curl -X POST \
72+
http://localhost:3000/ \
73+
-H 'content-type: application/json' \
74+
-d '{
75+
"username": "babel"
76+
}'
77+
```
78+
79+
### API testing tool
80+
81+
Instead of cURL, you can use an API testing tool like Postman or Insomnia. You can even save your requests and organise them into folders. Using those tools, compose a request to "http://localhost:port/" where `port` is the port that your server is listening to.
82+
83+
## Exercises
84+
85+
1. Create a new Node.js project
86+
2. Install express
87+
3. Create your first server
88+
4. Start and leave your server running
89+
5. Use cURL and Postman to test your server, send GET, POST, PUT, DELETE requests

docs/fundamentals/http.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,10 @@ Source: [https://www.youtube.com/watch?v=LtNSd_4txVc](https://www.youtube.com/wa
147147
#### Commonly used status codes
148148

149149
- 200 OK: The request is successful. The meaning of success depends on the request method. The response includes information.
150+
- 201 Created: The request has been fulfilled, resulting in the creation of a new resource
150151
- 204 No Content: The server successfully processed the request, but is not returning any content
151-
- 301 Moved Permanently: The resource requested has permanently moved to the URL given by the Location headers. Browsers and search engines can be redirected.
152+
- 301 Moved Permanently: The resource requested has permanently moved to the URL given by the Location headers. Browsers and search engines can be redirected. This could be important for SEO. This will also retain users and provide more information than 404.
153+
- 400 Bad Request: The request could not be understood by the server due to malformed syntax
152154
- 401 Unauthorized: The access is not authorized.
153155
- 403 Forbidden: The access is forbidden and the response includes information on access denied.
154156
- 404 Not Found

0 commit comments

Comments
 (0)