本地Fetch远程JSON遇SyntaxError,已设mode:no-cors求排查
问题
本地运行代码时,尝试从远程服务器拉取JSON文件,为绕开CORS错误设置了mode: "no-cors",但执行后报错:
dex.js:120 Uncaught (in promise) SyntaxError: Unexpected end of input
错误出现在const jsonData = await response.json();这一行,代码如下:
async function logJSONData() { const response = await fetch("https://leafpark.city/data/test.json",{ mode: "no-cors", // no-cors, *cors, same-origin cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached credentials: "same-origin", // include, *same-origin, omit headers: { // "Content-Type": "application/json", 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: "follow", // manual, *follow, error referrerPolicy: "no-referrer" // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url }); const jsonData = await response.json(); initMap(jsonData); return(jsonData); } let jsonData = logJSONData();
原因与解决方法
mode: "no-cors"是核心问题
设置mode: "no-cors"后,浏览器会返回一个不透明响应(opaque response)——这种响应的内容完全不可读取,哪怕服务器确实返回了JSON,也无法用response.json()解析,直接触发“意外的输入结束”错误。no-cors只是让请求不被浏览器拦截,但根本拿不到有效数据。请求头设置多余且错误
你请求的是JSON文件,却设置了Content-Type: application/x-www-form-urlencoded,这完全没必要。GET请求不需要设置Content-Type,如果要指定期望接收的类型,应该设置Accept: application/json,或者直接删掉这个多余的请求头。正确的解决路径
- 删除
mode: "no-cors":这是获取数据的前提,否则永远无法读取响应内容。 - 配置远程服务器CORS策略:让
leafpark.city服务器添加Access-Control-Allow-Origin响应头,值设为你本地服务器的域名(比如http://localhost:8080),测试阶段可以临时用*(生产环境不建议)。 - 使用本地代理转发请求:如果无法修改远程服务器配置,就在本地搭建代理服务器,将请求转发到远程地址。比如用Vite、Webpack的内置代理功能,或者自己用Node.js写简单代理,让浏览器请求同域的代理服务,避免触发CORS限制。
- 删除
内容的提问来源于stack exchange,提问作者Ferex
相关产品推荐
相关产品推荐

