I've created a little api using micro.
Running localhost:3000/get-status
should return the data object.
So far the console.log()
is printing the expected object.
But on the browser I get Endpoint not found
and on the server I get the error Si7021 reset failed: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
What am I doing wrong with my getStatus()
function? I guess I've mixed up something with the promises and asynchronous things. And maybe I've nested the functions unnecessarily...
const { send } = require('micro')
const { router, get } = require('microrouter')
const Si7021 = require('si7021-sensor')
const getStatus = async (req, res) => {
const si7021 = new Si7021({ i2cBusNo: 1 })
const readSensorData = async () => {
const data = await si7021.readSensorData()
console.log(data)
send(res, 201, { data })
}
si7021.reset()
.then((result) => readSensorData())
.catch((err) => console.error(`Si7021 reset failed: ${err} `))
}
const notFound = (req, res) => {
console.log('NOT FOUND.')
send(res, 404, 'Endpoint not found')
}
module.exports = router(
get('/get-status', getStatus),
get('/*', notFound)
)