VSCode 本地调试 html 无法获取外部数据
错误特征
Access to XMLHttpRequest at 'file:///<name>.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome-untrusted, https, edge.
产生原因
使用 file:// 直接访问本地文件,存在安全隐患,在最新版浏览器中默认被限制
解决方案
1. 配置调试文件
json
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "msedge",
"request": "launch",
"name": "启动 Edge",
"file": "${workspaceFolder}",
"runtimeArgs": ["--allow-file-access-from-files"]
}
]
}
2. 使用 Live Server 插件
安装后选择要打开的文件,鼠标右击后点击 Open With Live Server