Javascript导入/导出CORS问题

Javascript imports / exports CORS problem

我需要从包含 3 个 类 的某个 javascript 文件创建一个 类 的实例,并从另一个 [=29] 调用那个 类 的方法=] 文件。 类 在主 javascript 文件中是这样的:

function Class1(param1, param2) {
    this.openTag;
    this.closeTag;
    this.htmlTags;

    this.openTag = '<div id="' + this.elementId + '">';
    this.closeTag = '</div>';

    this.htmlTags = {
        sectionTitle: {
            openTag: '<h2 class="class1">',
            closeTag: '</h2>'
        },
        group: {
            openTag: '<div class="class2">',
            closeTag: '</div>'
        },
        table: {
            openTag: '<table class="class3">',
            closeTag: '</table>'
        }
    }
   ...
}

以及类似的方法:

 Class1.prototype.someName = function (index) {
    var outputHtml = '';

    var text = this.tableHeaders[index] || '';

    outputHtml += '<th>' + text + '</th>';

    return outputHtml;
}

如何创建这些 类 的实例并从另一个 javascript 文件中调用它们,或者如何在 HTML 中使用它们?当我尝试执行 ES6 imports/exports 或创建引用那些 类 的新对象时,它给我这个错误:

Access to script at 'file:///Users/user/Desktop/project/someName.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

&

app.js:1 Uncaught SyntaxError: Cannot use import statement outside a module

如果您的项目是使用 npm 创建的,那么

javascript 模块效果最好,即您没有在 index.html 底部加载脚本文件。如果你确实在底部加载脚本,你可能需要做这样的事情

<script type="module">

       import btn from './helper'

   </script>

所以,我解决了我的问题。我没有使用 node.js。我试图从另一个文件调用函数并将它们显示在 HTML 文件中。但是 CORS 政策不允许我使用它们。我所做的是,在 VS Code 上安装 Live Server 扩展。

启动 localhost 服务器,问题解决。因为你需要的是http://。因为当您打开 HTML 文件时,它会从 file:// 加载模型,这会导致问题。您可以通过打开 HTML 文件并右键单击编辑器并单击 Open with Live Server.

来简单地启动 localhost

我使用了 const abc = new Class();abc.someMethod(); 等实例。

重要提示

不要忘记将 script 标签添加到您的 HTML 并确保您的主要 script 标签位于其他标签下方,例如:

 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
 <script src="./readyFunctions.js"></script> <!-- Functions you will call -->
 <script src="./main.js"></script> <!-- js file where you call functions -->

另一个重要的注意事项是,如果您在按照我的指示操作后仍遇到此类错误,请确保您的 script 标签没有 type= "module".

您还可以查看 this post 以了解其他类型的解决方案。希望对您有所帮助:)