Отображение Json из Node.js на графике. js с React - PullRequest
0 голосов
/ 16 апреля 2020

Я получаю JSON Объект из mysql базы данных с Node.js. Чем я хочу отобразить его в реальном времени с помощью Chart. js и React, но обо всем по порядку. Для получения json это мой код: (script.js)

const mysql=require('mysql')
const express=require('express')
var app=express();

var mysqlConnection=mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password:'',
    database:'sampledb'
});

mysqlConnection.connect((err)=>{

    if(!err){
        console.log('DB Connection sucessful');
    }else{
        console.log('DB Connection failed \n Error:' +JSON.stringify(err,undefined,2));

    }
});


app.listen(3001,()=>console.log('Express server is running at port: 3001'));


//Get all
app.get('/', (req, res) => {
    mysqlConnection.query('SELECT * FROM mysampletable', (err, rows, fields) => {
        if (!err){
            res.send(rows);//this gives me my JSON
            console.log(rows);
        }

        else
            console.log(err);
    })
});

Так что я не понимаю, как я могу получить объект json в реальном времени, чтобы я мог отобразить его с помощью диаграммы. js и реагировать. Например, я получил небольшой фрагмент кода для отображения следующих данных (App.js):

import React, {Component} from 'react';
import './App.css';
import Chart from './components/Chart'


class App extends Component{

    constructor() {
        super();
        this.state={
            chartData:{

            }
        }
    }


    componentDidMount() {
        this.getchartData();
    }


    getchartData = () => {
        // Make request to the node backend. You might need to enable CORS in the express app.
        fetch("http://localhost:3001/")
            .then(res => res.json())
            .then((jsonarray) => {
                var labels = jsonarray.map(function(e) {
                    return e.Name;
                });
                var data = jsonarray.map(function(e) {
                    return e.Value;
                });

                console.log(labels,data);

                this.setState({
                    chartData:{
                        labels:labels,
                        datasets:[
                            {
                                label:'Popuplation',

                                data:data
                            }
                        ]
                    }
                });
            });
    };   

    render(){
        return(
            <div className="App">
                <header className="App-header">

                    <Chart chartData={this.state.chartData} location="Test" legendPosition="bottom"/>
                </header>
            </div>

        );
    }
}

export default App;

Эта строка console.log(labels,data); дает следующий вывод в веб-браузере (консоль Firefox):

Array(4) [ "Test", "Testtwo", "Test", "Testtwo" ]
 Array(4) [ 5, 10, 5, 10 ]

В Microsoft Edge я получаю следующий ответ:

Test,Testtwo,Test,Testtwo 5,10,5,10

Для полноты моей рабочей диаграммы. js ведьма отображает диаграмму:

import React, {Component} from "react";
import {Line} from 'react-chartjs-2';


class Chart extends Component{
    constructor(props) {
        super(props);
        this.state={
            chartData:props.chartData
        }
    }

    static defaultProps={
        displayTitle:true,
        displayLegend:true,
        legendPosition:'right',
        location:'City'


    }

    render() {
        return(
            <div className="Chart">

                <Line
                    data={this.state.chartData}
                    options={{
                        title:{
                            display:this.props.displayTitle,
                            text: 'Largest Cities in ' + this.props.location,
                            fontsize:25
                        },
                        legend:{
                            display:this.props.displayLegend,
                            position:this.props.legendPosition
                        }

                    }}
                />
            </div>
        );
    }

}

export default Chart;

Благодарен за любая помощь

1 Ответ

0 голосов
/ 16 апреля 2020

Вам необходимо использовать fetch, чтобы сделать вызов API для серверной части.

getchartData = () => {
    // Make request to the node backend. You might need to enable CORS in the express app.
    fetch("http://localhost:3000/") 
    .then(res => res.json())
    .then((jsonarray) => {
        var labels = jsonarray.map(function(e) {
            return e.Name;
        });
        var data = jsonarray.map(function(e) {
            return e.Value;
        });

        this.setState({
            chartData:{
                labels:labels,
                datasets:[
                    {
                        label:'Popuplation',

                        data:data
                    }
                ]
            }
        });
    });
}

Также вы можете удалить состояние в Chart.js, так как оно не нужно, и напрямую использовать реквизиты.

render() {
        return(
            <div className="Chart">

                <Line
                    data={this.props.chartData}


                ...

Рабочая Stackblitz пример

...