3 回答
TA贡献1862条经验 获得超6个赞
您的代码是从“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"
还有一些浏览器扩展可以“解锁”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);
TA贡献1860条经验 获得超9个赞
在客户端,您将无法获取 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端点来查询客户端代码中的数据。
TA贡献1785条经验 获得超4个赞
看看这里并向下滚动到“供应请求选项”:
fetch(
'https://github.com/ProjectSakura/OTA/blob/10/changelog/changelog_beryllium.txt',
{
mode: 'no-cors'
}
)
添加回答
举报