JavaScript的导入/导出CORS问题

3

我需要创建一个特定javascript文件中的类的实例,该文件包含3个类,并从另一个javascript文件调用这些类的方法。主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导入/导出或创建引用这些类的新对象时,会出现以下错误:
来自 'null' 的脚本访问 'file:///Users/user/Desktop/project/someName.js' 已被 CORS 策略阻止:跨源请求不支持协议方案:http、data、chrome、chrome-extension、https。

以及 app.js:1 Uncaught SyntaxError: Cannot use import statement outside a module
2个回答

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

它启动了一个本地服务器,问题就这样解决了。因为你需要使用 http://。当你打开 HTML 文件时,它会从 file:// 加载模型,导致了问题。你可以通过打开一个 HTML 文件并右键单击编辑器,然后点击 Open with Live Server来简单启动 localhost

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

重要提示

不要忘记在你的 HTML 中添加 script 标签,并确保你的主要 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"。您也可以查看此帖子以获取其他解决方案。希望能帮到您 :)

0

如果您的项目是使用npm创建的,即您没有在index.html底部加载脚本文件,则JavaScript模块将最有效地工作。如果您确实在底部加载了脚本,则可能需要执行类似于以下操作:

<script type="module">

       import btn from './helper'

   </script>

该项目并非使用npm创建的,而只是一个带有ECMAScript 5的单个js文件。导入/导出是ES6的功能,因此我不知道如何从另一个文件中调用函数。 - Ömürcan Cengiz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接