[英]How to fetch data in option tags in html from a `.txt` or `.css` file?
[英]How to fetch data from a particular github txt file in html page via javascript
我想获取这个 url 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();
有什么方法可以获取 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
这是错误日志
编辑2:
JavaScript 中的 Promises/Fetch:如何从文本文件中提取文本
从 GitHub 读取代码作为 web 页面中的文本(原始)
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
这是我在写问题之前发现的链接
您的代码是从与“http://github.com”不同的“http://127.0.0.1:5500”部署的,并且被CORS (默认情况下在现代浏览器上启用)阻止。 您需要将特定标头添加到您的开发服务器。
Access-Control-Allow-Origin header 中的 * 允许与任何(通配符)域进行通信。
样本:
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, Content-Type, Authorization"
还有一些浏览器扩展可以“取消阻止”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);
在客户端,您将无法获取 GitHub 文本文件,因为浏览器强制执行跨浏览器源策略作为安全措施。 您的源本身必须设置相关的 CORS 标头以允许这样做。 但是,您可以从服务器端执行此操作。 使用 express 创建如下所示的节点服务器,然后尝试从您自己的服务器访问数据。
服务器.js
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');
const app = express();
app.use(cors());
app.get('/txt_response', async (req, res) => {
const resp = await fetch('https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt');
const textResp = await resp.text();
res.json(textResp);
});
app.listen('9000');
现在您可以使用http://localhost:9000/txt_response
作为端点来查询客户端代码中的数据。
看看这里并向下滚动到“供应请求选项”:
fetch(
'https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt',
{
mode: 'no-cors'
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.