Aru*_*run 2 javascript fetch promise cors async-await
我想获取这个网址的数据https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt#L2
我正在尝试使用 fetch api 来获取数据,但我收到了 cors 错误
这是我想要做的
async function showmodal1() {
console.log("hello")
const data = await
fetch('https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt');
console.log(data)
}
showmodal1();
Run Code Online (Sandbox Code Playgroud)
有什么方法可以获取 github txt 文件的数据我尝试通过互联网找到它,但我找不到任何东西提前谢谢您的帮助
编辑:
Access to fetch at 'https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. changelog.html:361
GET https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt net::ERR_FAILED
showmodal1 @ changelog.html:361
(anonymous) @ changelog.html:365
dispatch @ jquery.min.js:3
r.handle @ jquery.min.js:3
changelog.html:364
Uncaught (in promise) TypeError: Failed to fetch
Run Code Online (Sandbox Code Playgroud)
这是错误日志
编辑2:
JavaScript 中的 Promises/Fetch:如何从文本文件中提取文本
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
这是我在写问题之前发现的链接
您的代码是从“http://127.0.0.1:5500”部署的,这与“http://github.com”不同,并且被CORS(默认情况下在现代浏览器上启用)阻止。您需要将特定的标头添加到您的开发服务器。
Access-Control-Allow-Origin 标头中的 * 允许与任何(通配符)域进行通信。
样本:
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, Content-Type, Authorization"
Run Code Online (Sandbox Code Playgroud)
还有一些浏览器扩展可以“解除阻止”CORS,但会被认为是不利的。
编辑:
获取原始源。通过单击您尝试在请求中访问的 URL 上的原始按钮,可以使用该 URL。
Edit2:这是可以工作的代码
const url1 = 'https://raw.githubusercontent.com/ProjectSakura/OTA/10/changelog/changelog_beryllium.txt'
const response = await fetch(url1);
const data = await response.text();
console.log(data);
Run Code Online (Sandbox Code Playgroud)