Scala版Play框架下JS文件无法加载公共资产中CSV文件怎么办?
The core issue here is relative path resolution—your JavaScript is trying to load data.csv relative to the current page's URL, not the location of line_graph.js itself. Here's how to fix it step by step:
1. Understand the Path Problem
When you use d3.csv("data.csv") in line_graph.js, the browser sends a request to http://your-domain/data.csv (relative to the page you're viewing), not the correct path http://your-domain/assets/js/data.csv. Play's Assets routing serves files from the /public directory at /assets/*, so you need to reference the CSV using its full asset URL.
2. Pass the Correct CSV URL to Your JavaScript
Since static JS files can't directly use Play's @routes.Assets.at template helper, you'll need to inject the correct URL from your HTML page:
Option 1: Use a Global Variable
Add this script block before loading line_graph.js in your HTML:
<script type="text/javascript"> // Inject the full CSV path using Play's route helper window.csvDataPath = "@routes.Assets.at("js/data.csv")"; </script> <script src="@routes.Assets.at("js/line_graph.js")" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.js"></script>
Then update your line_graph.js to use this global variable:
d3.csv(window.csvDataPath, function(error, data) { if (error) throw error; data.forEach(function(d) { d.number = d.number; d.iteration1 = +d.iteration1; d.iteration2 = +d.iteration2; }); // Rest of your graph logic });
Option 2: Pass the Path as a Function Parameter
If your JS uses an initialization function, pass the URL directly when calling it:
In your HTML:
<script src="@routes.Assets.at("js/line_graph.js")"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.js"></script> <script type="text/javascript"> // Initialize the graph with the correct CSV path initLineGraph("@routes.Assets.at("js/data.csv")"); </script>
In line_graph.js:
function initLineGraph(csvUrl) { d3.csv(csvUrl, function(error, data) { if (error) throw error; data.forEach(function(d) { d.number = d.number; d.iteration1 = +d.iteration1; d.iteration2 = +d.iteration2; }); // Rest of your graph logic }); }
3. Verify Your Setup
- First, test if the CSV is accessible directly: Visit
http://your-domain/assets/js/data.csvin your browser. If it downloads the file, your Play Assets routing is configured correctly (your current route and file structure look right). - Check your browser's dev tools (Network tab) to confirm the CSV request is going to the correct URL after making the changes.
4. CSP Configuration Check
Your current CSP setting default-src * allows loading assets from your own domain, so this shouldn't block the CSV request. If you still see CSP errors, you can explicitly add 'self' to img-src or media-src (though CSV falls under default-src here, so it should be fine).
内容的提问来源于stack exchange,提问作者Curious

