【发布时间】: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