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 athttp://localhost:8081/foo, it’ll callhttp://localhost:8081/foo/statusinstead ofhttp://localhost:8081/status). - String-to-Number Conversion: The
last_valuereturned 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
yValinside the loop withlet 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
setIntervalwith an async function can lead to overlapping requests if the API call takes longer than your interval time. A better approach is to use recursivesetTimeoutto 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
- Make sure your server is running on
http://localhost:8081and you’re accessing your client page from the same origin. - Open your browser’s DevTools (F12) → Network tab, and check that the
/statusrequests are returning a 200 OK response with the correctlast_value. - Check the Console tab for any fetch errors or type-related warnings—this will help catch any remaining issues.
内容的提问来源于stack exchange,提问作者Chandan Kumar
相关产品推荐
相关产品推荐

