VS Code调试模式下fetch()函数无法正常工作的原因排查
问题:VS Code调试模式下fetch本地文件失败,但Live Server运行正常
我在VS Code里用Live Server运行项目时,用fetch()获取txt文件能得到预期结果,代码如下:
let file = "/files/mensaje.txt" fetch(file) .then(x => x.text()) .then(y => document.getElementById("letrero").innerHTML = y);
但进入调试模式时,会抛出Uncaught TypeError TypeError: Failed to fetch错误,错误栈信息如下:
Uncaught TypeError TypeError: Failed to fetch at test (c:\Users\User\Desktop\Desarrollo Profesional\Cursos Desarrollador\JS Curso 2022\important_concepts_fetch.html:32:7) at onclick (c:\Users\User\Desktop\Desarrollo Profesional\Cursos Desarrollador\JS Curso 2022\important_concepts_fetch.html:16:42) --- Promise.then --- at test (c:\Users\User\Desktop\Desarrollo Profesional\Cursos Desarrollador\JS Curso 2022\important_concepts_fetch.html:34:8) at onclick (c:\Users\User\Desktop\Desarrollo Profesional\Cursos Desarrollador\JS Curso 2022\important_concepts_fetch.html:16:42) test @ c:\Users\User\Desktop\Desarrollo Profesional\Cursos Desarrollador\JS Curso 2022\important_concepts_fetch.html:32:7
这不是我第一次遇到这种问题,其他项目也存在Live Server运行正常但调试报错的情况。当前的launch.json配置如下:
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Open important_concepts_fetch.html", "file": "c:\\Users\\User\\Desktop\\Desarrollo Profesional\\Cursos Desarrollador\\JS Curso 2022\\important_concepts_fetch.html" } ] }
解决方法
问题核心是调试模式直接通过file://协议打开本地文件,而浏览器的fetch API在file://协议下会受跨域安全限制;Live Server是通过http://协议启动本地服务器,所以不存在这个问题。
方案1:修改调试配置,通过HTTP协议调试
- 先启动Live Server,确认项目的访问地址(默认一般是
http://127.0.0.1:5500/important_concepts_fetch.html) - 修改
launch.json配置,用url字段指向Live Server地址,同时指定项目根目录:
{ "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Debug with Live Server", "url": "http://127.0.0.1:5500/important_concepts_fetch.html", "webRoot": "${workspaceFolder}" } ] }
方案2:调整fetch路径为相对路径
将绝对根路径改为相对路径,适配文件层级:
// 用相对路径代替绝对根路径 let file = "./files/mensaje.txt" fetch(file) .then(x => x.text()) .then(y => document.getElementById("letrero").innerHTML = y);
两种方案都能让调试模式下的fetch正常工作。
内容的提问来源于stack exchange,提问作者David98761324
相关产品推荐
相关产品推荐

