浏览器将本地文件视为跨域请求,因此需要在本地运行一个服务器来模拟跨域请求。可以使用node.js的http-server模块来启动一个简单的本地服务器。
步骤1:安装http-server模块。在命令行中输入以下命令并运行:
npm install http-server -g
步骤2:在本地文件所在的目录中运行http-server命令。
cd path/to/file
http-server
步骤3:浏览器中打开本地服务器的地址,可以使用localhost:8080或127.0.0.1:8080等。
http://localhost:8080/index.html
这样就可以使用fetch来访问本地文件了。例如:
fetch('data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));