如何通过javascript从html页面中的特定github txt文件中获取数据

如何知道elem的价值arr


function a(num){

  function ab(elem){

        let num=6

        return elem.length>num;

    }

    return ab;

  }


let arr=['caterpillar','justin','openhome'];

console.log(arr.filter(a()));我想获取这个 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

这是错误日志


汪汪一只猫
浏览 224回答 3
3回答

阿波罗的战车

您的代码是从“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);

慕码人2483693

在客户端,您将无法获取 GitHub 文本文件,因为浏览器强制执行跨浏览器源策略作为安全措施。您的来源本身必须设置相关的 CORS 标头以允许这样做。但是,您可以从服务器端执行此操作。使用 express 创建如下所示的节点服务器,然后尝试从您自己的服务器访问数据。服务器.jsconst 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'      })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript