To create a team, we need to implement the POST handler. The data to the new team will be sent into the body parameter into the HTTP Request. Apply the following changes to the teams-api.js file:
...
api
.route('/teams')
...
.post((req, res) => {
let team = req.body
teams.push(team)
res.status(201).json(team)
})
...
...
First, we read the data from the req.body property. Then, we insert the new element into the teams array. Lastly, we send the teams array with the new team added and specify the HTTP status 201, which means Resource Created.
To test things out, we will call our API using the following command:
$ curl -X POST -H "Content-Type: application/json" -d '{"id":3, "name": "Brasil"}' localhost:3000/teams
Our command is a little weird this time. As we are using JSON, we have to explicitly tell the HTTP Request that we are sending JSON data, so we use the -H header option. To send the information, we use the -d data option. That's all! It looks difficult but it is not.
Now you can use the GET method to list all the teams and see the new team added to our list.