简体   繁体   English

如何通过 fetch 从本地 JSON 文件中获取数据

[英]How to get data from a local JSON file with fetch

I reckon this might be an old topic but I begin with Javascript... I get this error in my Javascript base code: "Fetch API cannot load file:///C:/Users[...]data.json. URL scheme must be "http" or "https" for CORS request" I reckon this might be an old topic but I begin with Javascript... I get this error in my Javascript base code: "Fetch API cannot load file:///C:/Users[...]data.json. URL对于 CORS 请求,方案必须为“http”或“https”

All the answers I see online says that a local server is needed to use fetch with a file.我在网上看到的所有答案都说需要本地服务器才能对文件使用 fetch。 But I would need to find solutions without using a local server.但是我需要在不使用本地服务器的情况下找到解决方案。

Here is my code:这是我的代码:

function getData() { function getData() {

fetch('data.json')
    .then(res => res.json())
    .then(data => {
        console.log(data)
    })

}; };

getData();获取数据();

My files HTML et JS are well linked and my file data.json is located in the same folder.我的文件 HTML 等 JS 链接良好,我的文件 data.json 位于同一文件夹中。

Somebody (who has understood my problem:) could give me some help/advice please?有人(谁了解我的问题:)可以给我一些帮助/建议吗? Thanks谢谢

It is not very wise to make that decision if you can avoid it, but there are different free websites that you could use in the same exact way, for example extendsclass.com has a free json server that you can use to make your own server.如果可以避免,做出该决定不是很明智,但是您可以以相同的方式使用不同的免费网站,例如extendsclass.com有一个免费的 json 服务器,您可以使用它来制作自己的服务器. All you have to do is make an account and send a fetch request to the api that they give you (with a limit of 10,000 request per month).您所要做的就是创建一个帐户并向他们给您的 api 发送一个获取请求(每月请求限制为 10,000 个)。

I think js via browsers cannot have access to local file for security reasons.我认为出于安全原因,通过浏览器的 js 无法访问本地文件。

you have to use node js to extract data.您必须使用节点 js 来提取数据。

or trying some free api to prevent this problem.或尝试一些免费的 api 来防止这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM