HTML页面可访问SVG文件夹但无法加载SVG文件的问题求助
SVG文件加载404错误排查与解决
我正在用HTML开发一款游戏,搭建了测试页面验证功能,想通过JavaScript把/assets/svg/props/items文件夹里的SVG文件加载到页面里。写的代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SVG Gallery</title> </head> <body> <h1>SVG Gallery</h1> <div id="svg-container"></div> <script> async function fetchSVGs() { try { const response = await fetch('/assets/svg/props/items'); const text = await response.text(); // 解析目录列表提取SVG文件名 const parser = new DOMParser(); const doc = parser.parseFromString(text, 'text/html'); const links = Array.from(doc.querySelectorAll('a')) .filter(link => link.href.endsWith('.svg')); // 动态加载每个SVG文件 const container = document.getElementById('svg-container'); links.forEach(link => { const svgPath = link.getAttribute('href'); const img = document.createElement('img'); img.src = svgPath; container.appendChild(img); }); } catch (error) { console.error('Error loading SVGs:', error); } } fetchSVGs(); </script> </body> </html>
代码能访问目标目录并获取到SVG文件列表,但加载时出现Failed to load resource: the server responded with a status of 404错误,没法加载SVG文件。
问题原因
从目录列表里拿到的href属性是相对文件名(比如shield.svg),浏览器会以当前页面的URL为基准拼接路径。如果你的测试页面不在/assets/svg/props/items/路径下,最终请求的SVG地址就会出错,返回404。
修复方案
给SVG路径拼接完整的基础路径,确保请求地址正确:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SVG Gallery</title> </head> <body> <h1>SVG Gallery</h1> <div id="svg-container"></div> <script> async function fetchSVGs() { try { // 定义SVG文件夹的基础绝对路径 const baseSvgPath = '/assets/svg/props/items/'; const response = await fetch(baseSvgPath); const text = await response.text(); const parser = new DOMParser(); const doc = parser.parseFromString(text, 'text/html'); const links = Array.from(doc.querySelectorAll('a')) .filter(link => link.href.endsWith('.svg')); const container = document.getElementById('svg-container'); links.forEach(link => { // 提取文件名,拼接完整绝对路径 const svgFileName = link.getAttribute('href'); const img = document.createElement('img'); img.src = baseSvgPath + svgFileName; // 可选:添加alt属性优化可访问性 img.alt = svgFileName.replace('.svg', ''); container.appendChild(img); }); } catch (error) { console.error('Error loading SVGs:', error); } } fetchSVGs(); </script> </body> </html>
额外排查点
- 确认服务器已开启目录列表功能:比如Apache需要配置
Indexes指令,Nginx需要开启autoindex on,否则无法获取文件列表。 - 检查SVG文件路径和文件名:确保文件实际存在,且大小写和代码里的路径一致(部分服务器区分大小写)。
- 开发服务器配置:如果用Vite、Webpack Dev Server这类工具,确认静态资源目录配置正确,
/assets能被正常访问。
内容的提问来源于stack exchange,提问作者bruh who is you
相关产品推荐
相关产品推荐

