【问题标题】:Reading the content of a JS file using JS使用JS读取一个JS文件的内容
【发布时间】:2021-10-02 03:36:19
【问题描述】:

我正在尝试读取脚本标记中包含的 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.

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

【问题讨论】:

    标签: javascript dom cors fetch


    【解决方案1】:

    Fetch api 只在实时服务器上有效,正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 2022-06-11
      • 1970-01-01
      相关资源
      最近更新 更多