【问题标题】:How to fetch data in ReactJS from NodeJS API for Influxdb?如何从 Influxdb 的 NodeJS API 中获取 ReactJS 中的数据?
【发布时间】:2018-06-22 08:17:00
【问题描述】:

我使用 InfluxDB 作为数据库,我使用 influxdb-nodejs 库模块创建 API 以从 Influxdb 写入数据和查询数据。

Queryfunction.js API 代码如下:

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);
  }
}

我使用 script.js 文件在 Queryfunction.js API 中调用 queryfunc():

const myModule = require('./Queryfunction');
let val = myModule.queryfunc();

我使用命令节点脚本来运行脚本文件。 结果是一个数组 C:\Users\Admin\Desktop\reactApp\API>节点脚本

{ 结果:[ { statement_id: 0, series: [Array] } ] }

我正在使用 ReactJS 创建前端 UI 组件。如何在 ReactJS 中获取结果数组数据?

【问题讨论】:

  • 你必须先创建rest api 使用express.js 来创建rest api

标签: node.js reactjs influxdb


【解决方案1】:

您要么需要写入 json 文件,要么需要在 db 调用周围有一个快速包装器。

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'))

在 react 中你做一个 fetch:

Class App extends React.Component {
  componentDidMount() {
    fetch('http://localhost:3000')
     .then(res => res.json())
     .then(data => this.setState( {data} ) )

  render() {
   ....
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2021-09-29
    相关资源
    最近更新 更多