首页 > 解决方案 > 使用JS读取一个JS文件的内容

问题描述

我正在尝试读取脚本标记中包含的 javascript 文件中的内容。

const script = document.querySelector("script");

fetch(script.getAttribute('src'))
.then((res) =>
    res.text().then((txt) => {
                 console.log(txt);
                 //this will have the content of the file
                })
  ).catch((err) => console.log(err));
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>

    <script src="index.js"></script>
    <script src="reader.js"></script>
    <!--reader.js will read the content of index.js file-->
  </body>
</html>

我收到以下错误

Fetch API cannot load file:///C:/Users/intel/OneDrive/Desktop/devl/index.js. URL scheme must be "http" or "https" for CORS request.

我知道如果我使用实时服务器它会工作,但是,如果我不使用实时服务器,我想知道如何使它工作。

标签: javascriptdomcorsfetch

解决方案


Fetch api 仅适用于实时服务器,这是正常的。


推荐阅读