使用Chart.js时遭遇Cross-Origin Read Blocking (CORB)错误,请求技术帮助
Hey there! Let's get that Cross-Origin Read Blocking (CORB) error sorted out for you.
What's causing the error?
The CORB error is popping up because you're trying to load a web page (text/html) from https://cdnjs.com/libraries/Chart.js instead of the actual Chart.js JavaScript file. Browsers block cross-origin HTML responses via CORB to protect security, which is exactly what's happening here.
How to fix it
Here are the key steps to resolve this:
Use the correct Chart.js CDN URL
You need to link directly to the minified JavaScript file hosted on cdnjs, not the library's landing page. For example, use this stable version URL (you can check for newer versions on cdnjs if needed):<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.8/chart.umd.min.js"></script>Avoid variable name conflicts
Your code usesconst Chart = document.getElementById("lineChart");which will clash with the globalChartobject that Chart.js exposes. Rename this variable to something likechartCanvasto prevent issues.
Modified Working Code
Here's your updated JavaScript with the fixes applied:
// Rename the variable to avoid conflict with Chart.js's global Chart const chartCanvas = document.getElementById("lineChart"); console.log(chartCanvas); let lineChart = new Chart(chartCanvas, { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", fill: false, lineTension: 0.1, backgroundColor: "rgba(75, 192, 192, 0.4)", borderColor: "rgba(75, 192, 192, 1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "#fff", pointBorderWidth: 1, pointHoverRadius: 5, pointHitRadius: 10, data: [65, 59, 80, 81, 56, 55, 40], } ] } });
Why this works
- The correct CDN URL returns a
application/javascriptMIME type, which browsers allow cross-origin, so CORB won't block it. - Renaming the variable prevents overwriting the global
Chartconstructor that Chart.js provides, ensuring your chart initializes correctly.
内容的提问来源于stack exchange,提问作者locrasm999

