I am using InfluxDB as database, I used influxdb-nodejs library module to create API to write data and Query data from Influxdb.
The Queryfunction.js API code is as follows:
module.exports = {
queryfunc: function() {
const Influx = require('influxdb-nodejs');
const client = new Influx('http://127.0.0.1:8086/mydb');
client.query('http')
.where('type', '2')
.then(console.info)
.catch(console.error);
}
}
I use a script.js file to call queryfunc() in Queryfunction.js API:
const myModule = require('./Queryfunction');
let val = myModule.queryfunc();
I use command node script to run the script file. The result is an array C:\Users\Admin\Desktop\reactApp\API>node script
{ results: [ { statement_id: 0, series: [Array] } ] }
I am using ReactJS to create front end UI components. How to fetch the resultant array data in ReactJS?
You're either need to write to a json file or you'll need to have an express wrapper around your db calls.
const express = require('express')
const app = express();
app.get('/api', (req, res, next) => {
const Influx = require('influxdb-nodejs');
const client = new Influx('http://127.0.0.1:8086/mydb');
client.query('http')
.where('type', '2')
.then(data => res.json(data)
.catch(err => next(err)); // error middleware to handle
}
app.listen('3000', () => console.log('running on http://localhost:3000'))
Within react you do a fetch:
Class App extends React.Component {
componentDidMount() {
fetch('http://localhost:3000')
.then(res => res.json())
.then(data => this.setState( {data} ) )
render() {
....
}
}