【问题标题】:Unable to load external scripts when debugging JavaScript in VisualStudioCode because of CORS [duplicate]由于 CORS [重复] 在 VisualStudioCode 中调试 JavaScript 时无法加载外部脚本
【发布时间】:2021-12-16 11:56:41
【问题描述】:

我想在Visual Studio Code (VSC) 中调试我的客户端 JavaScript 代码。但是,我想避免设置外部实时服务器,只想从本地驱动器加载文件。因此,我创建了以下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": "Launch Chrome from the file system",
            "file": "${workspaceFolder}/src/index.html"
        }
    ]
}

这执行得很好,当在 VSC 中使用F5 启动调试器时,Chrome 会打开并从src 文件夹加载我的index.html

但是,当我尝试像这样<script src="./index.js" type="module" defer></script> 导入我的index.js 文件时收到以下错误消息:

在“file:///home/matrix/odin-battleship/src/index.js”处访问脚本 CORS 政策已阻止来自原点“null”:跨原点 请求仅支持协议方案:http、data、chrome、 chrome-extension, chrome-untrusted, https.

我知道这是一项安全措施,可防止网站访问我的文件。我读过它here。但是,我只想在不创建实时服务器的情况下调试我的代码。我遇到了用标志--allow-file-access-from-files 启动 Chrome。 This question 解释了如何使用标志从 launch.json 启动 Chrome。

这是正确的尝试,还是有更好的解决方案可以从 VSC 的本地存储中调试文件?

【问题讨论】:

    标签: javascript visual-studio-code cors vscode-debugger


    【解决方案1】:

    正如您所提到的,这是浏览器强制执行的一项安全策略,以防止网站所有者访问您计算机上的文件。

    您应该开始从任何服务器分发此js 文件。这样您的scheme 将变为httphttps,并且文件可以安全地传送到浏览器。

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2014-04-11
      • 2015-07-07
      • 2019-03-12
      • 1970-01-01
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      相关资源
      最近更新 更多