javascript - 使用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.
我知道如果我使用实时服务器它会工作,但是,如果我不使用实时服务器,我想知道如何使它工作。
解决方案
Fetch api 仅适用于实时服务器,这是正常的。
推荐阅读
- json - 如何使用 Angular 中的 http 客户端和 Observables 遍历 JSON 对象数组
- authentication - 如何在 Jwt 模式下的 AdonisJs 中验证没有密码的用户?
- c - 如何识别静态变量的范围?
- r - JSS文章模板中的多个从属关系
- python - 使用 BeautifulSoup 抓取具有相同类名的多个数据
- python - 基于匹配列 pandas 组合行
- jquery - 将关闭按钮添加到使用 jquery 创建的查看器中?
- sql - 新客户订单,但前提是他们在注册后 1 周购买
- r - 在地图中使用 stat_countour() 的问题 (ggplot2.R)
- python - 是否可以将 TensorFlow 中的训练模型转换为可用于迁移学习的对象?