簡體   English   中英

無法從 Chrome 中的本地 html 文件獲取遠程 json 鏈接

[英]not able to fetch remote json link from local html file in chrome

我想從鏈接 [https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050] 中獲取 json 當我在瀏覽器中打開時,它會將 json 轉儲到屏幕上; 正如預期的那樣好,但是當我嘗試從 javascript 獲取此鏈接時,它給了我 cors 錯誤。

請通過提供可行的解決方案來幫助我。 我不是專業程序員。

最好我不想要中間的服務器。 服務器解決方案被認為是最后的選擇,如果沒有它是不可能的。 目前我在中間使用 nodejs 服務器。

運行代碼時出現錯誤

我在 javascript 中嘗試使用此代碼

fetch('https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
        },
    })
    .then(response => response.json())
    .then(response => console.log(JSON.stringify(response)))

這是由於缺少cors header。 CORS代表跨組織資源共享。 這個 header 告訴服務器/后端允許任何來源(如www.google.com )除了它自己的瀏覽器應該允許加載資源。

這是對您的代碼的修復

 fetch('https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050', { method: 'GET', headers: { 'Accept': 'application/json', 'Access-Control-Allow-Origin':'*', }, }).then(response => response.json()).then(response => console.log(JSON.stringify(response)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM