You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In this lecture we talk about Top Level Middleware, Using Postman, and using Axios in our API.
4
+
5
+
## Top Level Middleware
6
+
7
+
`Top Level Middleware` is the term we use to refer to some logic that will be executed upon every request that is made to our API.
8
+
9
+
We can set up that logic inside of the built method `.use()` that comes from the object that is return from invoking `express`.
10
+
11
+
```javascript
12
+
app.use(/* some function to execute here */);
13
+
```
14
+
15
+
## Req Body
16
+
17
+
Sometimes we need to send some complex data to our API. Using the `req.query` or `req.params` just might not be suffuciant enough to use to send this data. This is where the `body` comes into play.
18
+
19
+
`req.body` is the object we can use to receive the complex data. However, the data that comes from the body of the request is received as `JSON` so we need to parse it into a Javascript Object.
20
+
21
+
We can do this by using a special function from `express` called `express.json()`. This function will parse the JSON that comes as the `body` from the request and turn it into a useable object for us.
22
+
23
+
We want to invoke this function as `Top Level Middleware` so that it is invoked upon every connection made to our API.
24
+
25
+
We will pass it into our `app.use()` function to run it as top level middleware.
26
+
27
+
```javascript
28
+
app.use(express.json());
29
+
```
30
+
31
+
## CORS
32
+
33
+
CORS stands for `Cross Origin Resource Sharing`. This is a security protocol that we can use to safely allow other origins talk to our origin. This means that we can make a request from one server to another server.
34
+
35
+
We first need to install `CORS` as a dependency for our project. In the terminal, run:
36
+
37
+
```bash
38
+
$ npm install cors
39
+
```
40
+
41
+
Then require it at the top of the `index.js` file for our API.
42
+
43
+
```javascript
44
+
constcors=require('cors`)
45
+
```
46
+
47
+
Then we need this function to be invoked as top level middleware.
48
+
49
+
```javascript
50
+
app.use(cors())
51
+
```
52
+
53
+
Now your API is setup to follow the `CORS` protocol.
54
+
55
+
## Postman
56
+
57
+
`Postman` is a suite that we can use to act as a `client` to interact with the `API` that we build.
0 commit comments