05 - Sending the Response
In this module, we'll pass the request data back in our callback function
Overview
We now have a proper sequence, but the way we displayed the success message might not be what we want. We actually are probably going to want the data to be sent back to us after it's been saved in the db. The current response res.send("Step four");
is in no way really connected to the actual data. What if, for instance, we were saving an item to a To-Do list? We would want the data to save, and then we would want to get it in our response. Let's pass some of the data into the callback to provide a more detailed response to the user.
The Code
Go into the testcontroller.js
file and add the following method. Add it to the bottom of the file above the export statement.
It's important to note that the
.then()
method is chained to.create()
. In fact, the whole expression could be read like this in one line:With that idea in mind, we have changed the data coming back in the response to the data that was persisted in Postgres. To be clear, after the data is persisted in the Postgres with the
.create()
method and in thetestdata
column, the.then()
method returns a Promise that fires up a callback function holding the data that was just added.
It's important to note that the data
parameter can have any name that we want.
Testing
Let's use Postman to test this:
Make sure your server is running.
Open Postman.
Open a new request.
Change the dropdown to POST.
Enter the endpoint into the URL:
http://localhost:3000/test/five
.Click on the body tab under the url input field.
Choose the
raw
radio button.In the dropdown, choose
JSON (application/json)
.In the empty space, add a JSON object like the one below:
Press send.
You should see the following:
Notice that the data in the response matches the data in the request.
You should also go to Postgres and make sure the data is there and that the
testdata
column matches the request and response:
Summary of the Flow
In this module, the following flow is happening:
We make a POST request with Postman.
body-parser
breaks the request into JSON.The router sends the request to the
testcontroller
.The controller with the
/five
endpoint is called.The
req.body.testdata.item
is captured in thetestData
variable.We then use the Sequelize
create()
method to create the object to be sent to the DB.The object is sent to Postgres, which stores it.
After the data is stored, we fire the
then()
method, which returns a Promise.We call a method that takes in a parameter called
testdata
. It holds the response data.The method fires a response to Postman.
Last updated