Vanilla JS项目报错Uncaught Error: Cannot find module '26sb0'求助
问题解决:Uncaught Error: Cannot find module '26sb0'
核心问题及修复步骤
1. 移除重复的模块引入
你在index.html中同时引入了index.js和apiService.js作为模块,但index.js已经通过import语句加载了apiService.js,重复引入会导致模块解析异常,触发奇怪的模块找不到错误。修改index.html,只保留index.js的引入:
<script type="module" src="index.js" defer></script>
2. 优化顶层await的写法(可选兼容处理)
虽然ES模块支持顶层await,但部分旧版浏览器可能存在兼容问题。如果需要覆盖更广的环境,可将await逻辑包裹在异步函数中:
import { fetchData } from './apiService'; const randomRecipePath = "recipes/random?apiKey=xxxxxxxxxxxxxxxxxx"; async function init() { const testData = await fetchData(randomRecipePath); console.log(testData); } init();
3. 增加API请求错误捕获
为避免API返回非JSON数据或请求失败引发隐藏问题,在apiService.js中添加错误处理逻辑:
const apiUrl = 'https://api.spoonacular.com'; export const fetchData = async(path) => { try { const res = await fetch(`${apiUrl}/${path}`); if (!res.ok) { throw new Error(`API请求失败: ${res.status}`); } const data = await res.json(); return data; } catch (err) { console.error('数据获取失败:', err); throw err; // 抛出错误让调用方按需处理 } };
验证流程
- 保存所有修改后的文件
- 确保本地服务运行路径正确(以
src目录为静态资源根目录) - 打开浏览器控制台,确认模块错误消失且API数据正常打印
内容的提问来源于stack exchange,提问作者femas1
相关产品推荐
相关产品推荐

