You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

API获取数据无法在Canvas.js图表显示,yVal赋值失败求助

Fixing Canvas.js Chart Data Assignment Issue in Your Node.js & Client Code

Let’s walk through the problems preventing your yVal from being assigned correctly and get that chart working:

Key Issues Identified

  • Incorrect Fetch Path: Your client’s fetch('status') is missing a leading slash, which means it’ll try to fetch from the current page’s relative path (e.g., if your page is at http://localhost:8081/foo, it’ll call http://localhost:8081/foo/status instead of http://localhost:8081/status).
  • String-to-Number Conversion: The last_value returned from Adafruit’s API is a string, but Canvas.js requires numeric values for data points—this will cause the chart to ignore the values entirely.
  • Variable Shadowing: You’re re-declaring yVal inside the loop with let yVal, which is unnecessary and can lead to confusion (though it’s not the root cause here, it’s a good practice to fix).
  • Uncontrolled Async in setInterval: Using setInterval with an async function can lead to overlapping requests if the API call takes longer than your interval time. A better approach is to use recursive setTimeout to ensure each update completes before the next starts.

Fixed Client Code

class Uploader {
  constructor() {}
  async plotLastValue(){
    var dps = []; // dataPoints
    var chart = new CanvasJS.Chart("plotLastValue", {
      title :{
        text: "Load vs Time Graph"
      },
      axisX:{
        title: "time in hour",
        gridDashType: "dot",
        gridThickness: 2
      },
      axisY: {
        includeZero: false,
        title: "Load in kW",
        customBreaks: [{ startValue: 1, endValue: 50, interval: 10, maximum : 5 }]
      },
      data: [{
        type: "line",
        dataPoints: dps
      }]
    });
    var xVal = 0;
    var updateInterval = 1000;
    var dataLength = 20; // number of dataPoints visible at any point

    // Fixed: Added leading slash to fetch path, converted response to number
    async function get() { 
      let response = await fetch('/status'); // Fixed path
      let res = await response.json();
      return Number(res["last_value"]); // Convert string to number
    }

    // Fixed: Removed variable shadowing, handled async properly
    var updateChart = async function (count = 1) {
      for (var j = 0; j < count; j++) {
        const newYVal = await get(); // Use a new variable instead of shadowing
        dps.push({ x: xVal, y: newYVal });
        xVal++;
      }
      if (dps.length > dataLength) {
        dps.shift();
      }
      chart.render();
    };

    // Initial load
    await updateChart(dataLength);

    // Fixed: Use recursive setTimeout instead of setInterval to avoid overlapping calls
    const scheduleNextUpdate = async () => {
      await updateChart();
      setTimeout(scheduleNextUpdate, updateInterval);
    };
    scheduleNextUpdate();
  }
}

Quick Checks to Verify

  1. Make sure your server is running on http://localhost:8081 and you’re accessing your client page from the same origin.
  2. Open your browser’s DevTools (F12) → Network tab, and check that the /status requests are returning a 200 OK response with the correct last_value.
  3. Check the Console tab for any fetch errors or type-related warnings—this will help catch any remaining issues.

内容的提问来源于stack exchange,提问作者Chandan Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:22:32