【问题标题】:Parsing in a path of a local file path instead of api url in Javascript解析本地文件路径的路径而不是Javascript中的api url
【发布时间】:2021-01-14 14:05:36
【问题描述】:

在我的代码中,我使用以下代码引用 API

fetch('https://?....).then(response => {
                        return response.json();

但是我需要传入本地文件 (JSON) 而不是下面的 api url

fetch('file:///E:/testData.json')

我收到错误“URL scheme must be "http" or "https" for CORS request

如果有人能在这里指出正确的方向,我将不胜感激。在这种情况下如何解析本地 JSON?我在这里做错了什么

【问题讨论】:

标签: javascript json api


【解决方案1】:

你需要在你的项目中创建带有json文件的文件夹,并在这种模式下调用:

fetch('./api/some.json')
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

【讨论】:

  • 文件夹应该专门命名为“api”?
  • 你可以用你想要的名字
猜你喜欢
  • 2023-01-04
  • 2017-05-01
  • 1970-01-01
  • 2014-04-27
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
相关资源
最近更新 更多