尝试使用fetch()响应数据填充Chart.js图

时间:2018-11-20 07:11:49

标签: javascript node.js chart.js fetch

所以我有一个chartjs图。单击按钮后,我使用fetch()从节点服务器获取数据。 Web服务器将数据i.e. an array发送到浏览器。

问题:它没有使用fetch() response客户端文件中定义的myscript.js->填充图形。

我应该没有模板引擎就能做到吗?我在这里做什么,请帮忙。

节点服务器api-index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {

  // res.render('index', { title: 'Express' });
});

router.post('/', function(req, res, next) {
  if(req.body.name) {
    data = [100, 200, 150, 100];
  } else {
    data = [0, 0, 0, 0];
  }
  console.log(req.name);

   res.send(data);
});
module.exports = router;

客户端javascript-myscript.js,即fetch()

// make an ajax fetch request to the server for graph data and populate it.
document.getElementById("form").addEventListener("submit", function(event) {

    // get for inputs to send to server
    let name = document.getElementById("form-name").value;

    // event.defaultPrevented();    
    // give endpoint, and create a request to send
    fetch("/", {
        method: 'POST',
        headers: new Headers(),
        body: JSON.stringify({ name: name})
    }).then(function(response) {
            return response.json();
        }).then(function(myJson) {
        if(myJson !== null)
            populateGraph(myJson);
        console.log("populated data.")

    });

});


var ctx = document.getElementById("myChart");

function populateGraph(db_data) {
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
            datasets: [{
                label: '# of Votes',
                data: db_data,
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive:true,
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });

}

index.html

<html>

<head>
  <title>Express</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta charset="UTF-8">
  <link rel="stylesheet" href="/stylesheets/style.css">
</head>

<body>
<header>
    <h1>Express</h1>
    <p>Welcome to Express</p>
</header>
<section class="section-one">
    <div class="graph-wrap">
        <canvas id="myChart"></canvas>
      </div>
      <form id="form" method="POST">
        <input type="text" id="form-name" name="name" value="shahyan">
          <button type="submit">ACTIVATE</button>  
      </form>
</section>

  <script src="/javascripts/Chart.js"></script>
  <script src="/javascripts/myscript.js"></script>
</body>

</html>

app.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use(bodyParser.urlencoded({ extended: false })) 

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Adding the path to chartjs to the public/scripts folder
app.use('/javascripts', express.static(__dirname + '/node_modules/chart.js/dist/'));


app.use('/', indexRouter);
app.use('/users', usersRouter);

module.exports = app;

0 个答案:

没有答案