[英]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.