简体   繁体   English

无法从 Chrome 中的本地 html 文件获取远程 json 链接

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

I want to fetch a json from link [https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050] When I open in browser it dumps the json on screen;我想从链接 [https://www.nseindia.com/api/equity-stockIndices?index=NIFTY%2050] 中获取 json 当我在浏览器中打开时,它会将 json 转储到屏幕上; good as expected but when I try to fetch this link from javascript it gives me cors error.正如预期的那样好,但是当我尝试从 javascript 获取此链接时,它给了我 cors 错误。

Please help me by giving a working solution.请通过提供可行的解决方案来帮助我。 I am not a pro programmer.我不是专业程序员。

Preferably I don't want a server in middle.最好我不想要中间的服务器。 Server solution is considered as last option if not possible without it.服务器解决方案被认为是最后的选择,如果没有它是不可能的。 Currently I am using nodejs server in middle.目前我在中间使用 nodejs 服务器。

Error I get when I run code运行代码时出现错误

I tried with this code in javascript我在 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)))

This is due to cors header missing.这是由于缺少cors header。 CORS stands for cross orging resource sharing. CORS代表跨组织资源共享。 This header tells the server/backend to permit any origins (like www.google.com ) except its own from which a browser should permit loading resources.这个 header 告诉服务器/后端允许任何来源(如www.google.com )除了它自己的浏览器应该允许加载资源。

Here is the fix to your code这是对您的代码的修复

 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