Making the server response data-friendly

Our server is currently returning HTML responses. A humidity of 38% will give us this response:

    <strong>38</strong>

While this works for our current setup, it is not ideal for when we need raw data, like we do now for making our charts. It is far easier to convert raw data to HTML as opposed to doing the opposite, so we can make our sensor displays compatible for raw data as well.

The most popular standard for data interchange, and one that is almost universal now, is JavaScript Object Notation (JSON). JSON is a very simple data interchange specification that is used to serialize data that is exchanged between applications. As we have been programming in JavaScript the whole time, JSON should feel very familiar to us.

In this section, we will be modifying our application server to return JSON responses, as opposed to the HTML responses it is returning now, so that we can make use of the raw data in our charts as well.

In your index.js file, change the temperature and humidity API route handlers to the following code:

    app.get('/temperature', function (req, res) {
/**
* The express response object comes with a built in
`json` method
* This automatically converts its first argument into
a JSON string, and sends it along with the content type
headers as a response.
*/

res.json({
value:
getCachedSensorReadings.getTemperature().toFixed(1)
})
})

app.get('/humidity', function (req, res) {
res.json({
value:
getCachedSensorReadings.getHumidity().toFixed(1)
})
})
..................Content has been hidden....................

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