Configuring the JSON Parser

We will start by configuring our server to be able to parse JSON. This means that Express.js will automatically parse the data that flows in and out of the HTTP Request. The following diagram explains this:

As you can see, all the requests will be intercepted by the JSON Parser. The JSON Parser is better known as a middleware. A middleware is just a simple function that is processed before another function. For example, the GET /teams function is supposed to be the only function that should be called in every request, but as we have configured the JSON Parser, the GET /teams will be invoked once the JSON Parser function is completed.

To configure this in our code, first we need to install it. Run the npm install --save body-parser in your terminal and apply the following changes:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.json())

app.get('/teams', (req, res) => {

const teams = [{ "name": "Peru" }, {"name": "Russia"}]

res.json(teams)
})
...

First, we import the body-parser module. Then, we configure the application to use our bodyParser.json() using its app.use function. All the middleware are configured by calling this function.

Lastly, to test whether the JSON Parser is working, we define the teams variable containing two teams with their respective names. To send the teams, we use res.json instead of res.send. Let's check the results by executing the following command:

$ curl -X GET http://localhost:3000/teams

[{"name":"Peru"}, {"name":"Russia"}]

Now that our API is able to receive and send JSON, let's move our routes to its own file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset