2

First of all, I will apologize for another problem of this topic but after reading dozens of examples and solutions here I can't solve my problem and get it to work.

I wrote a script that communicates with an API and every 5 minutes it spits out an array with data. I save that in localstorage on my computer. That data I would like to put into a chart. Now I've used so many examples but I only get a static chart to work.

I have a server.js file and an index.html file. Both are examples I took from other posts and I'm trying to modify them to my needs.

I tried to:

=> include a .js file

error: "Not allowed to load local resource"

=> use document.getElementById in external file. same error

Server.js

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

var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html')
});

app.post('/submit-data', function (req, res) {
    res.send('POST Request');
});

app.put('/update-data', function (req, res) {
    res.send('PUT Request');
});

app.delete('/delete-data', function (req, res) {
    res.send('DELETE Request');
});

var server = app.listen(3000, function () {
    console.log('Node server is running..');
});

Index.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>API Chart!</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

  </head>
  <body>

    <canvas id="myChart" width="400" height="400"></canvas>
<script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var chart = new Chart(ctx, {
        // The type of chart we want to create
        type: 'bar',

        // The data for our dataset
        data: {
            labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
            datasets: [{
                label: 'My First dataset',
                backgroundColor: 'rgb(255, 99, 132)',
                borderColor: 'rgb(255, 99, 132)',
                data: [0, 10, 5, 2, 20, 30, 45] // this data needs to change
            }]
        },

        // Configuration options go here
        options: {}
    });

</script>

  </body>
</html>

What I need is the data inside the dataset to be dynamic. Every 5 minutes I want to push new data into the chart. How do I put a variable into my HTML file that contains my API data?

Bob W.
  • 21
  • 3
  • You can refer to https://stackoverflow.com/a/55018116/8305782: setInterval(function() { updateChart() }, 300000), where the chart will be updated every 5 minutes and updateChart function replaces the old dataset with the new one. – lmathl May 30 '19 at 01:11

0 Answers0