Modifying the sensor dashboards to consume JSON data

We must not forget that the sensor displays used earlier are currently set up to work with HTML text, not JSON data. In order to make it compatible, we will have to make a change to our script file. Fortunately, our code is made such that the only change to be made on our side is in the fetchTemperature and fetchHumidity functions:

    const fetchTemperature = () => { 
fetch('/temperature')
.then(results => {
/**
* We want the results converted to json, so we use
the fetch results' `json` method, which returns a promise
with the JSON data instead of the string
*/

return results.json()
})
.then(data => {
/**
* In our server API route handler, the format of
returned data was an object with a `value` property.
* The value of the sensor reading is therefore
available in `data.value`
*/

const temperatureDisplay =
document.getElementById('temperature-display')
/**
* We add in the HTML tags on the front end script
this time, leaving the backend to only provide us data
*/

temperatureDisplay.innerHTML = '<strong>' +
data.value + '</strong>'
})
}
/**
* Repeat the same steps for the humidity API
*/

const fetchHumidity = () => {
fetch('/humidity')
.then(results => {
return results.json()
})
.then(data => {
const humidityDisplay =
document.getElementById('humidity-display')
humidityDisplay.innerHTML = '<strong>' + data.value
+ '</strong>'
})
}

If you open your browser, the app should look exactly the same as it did earlier, which is a good thing because that means we can move on to utilizing this data to power our charts.

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

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