【问题标题】:Github pages, how to fetch file in js from repoGithub页面,如何从repo中获取js中的文件
【发布时间】:2022-12-30 02:01:18
【问题描述】:

我有一个要创建的 github 页面项目。我已经让它在本地运行良好,但是当我发布它时当然会失败。

问题出在这段 javascript 中,它应该从 repo 中的 json 文件中提取一些数据来构建某个页面的内容:

(async function(){
  const response = await fetch(`https://GITUSER.github.io/GITREPO/tree/gh-pages/data/file.json`);//Error gets thrown here, because the asset does not exist in the current code state.
  const docData = await response.json();
  const contentTarget = document.getElementById('doc-target');
  const tocTarget = document.getElementById('toc-target')
  createContent(tocTarget,contentTarget,docData);
})();

现在,问题是页面不会加载资产,因为在调用该函数之前它不知道它需要它。有没有办法让页面加载这个资产,以便它可以被 fetch API 调用?还是这超出了 github pages 的能力?

编辑:为上下文添加了一些额外的代码。

【问题讨论】:

  • 你能展示更多的代码吗
  • 补充说,尽管对于问题的最低限度复制来说,并没有太多其他内容。
  • 你试过记录json文件吗
  • 你是说 response 值?问题是它返回错误 404,而不是 json 文件本身。

标签: javascript github-pages fetch-api


【解决方案1】:

尝试像这样使用 raw.githubusercontent.com

(async function(){
  const response = await fetch('https://raw.githubusercontent.com/{username}/{repo}/{branch}/{file}')
  const docData = await response.json();
  const contentTarget = document.getElementById('doc-target');
  const tocTarget = document.getElementById('toc-target')
  createContent(tocTarget,contentTarget,docData);
})();

它会起作用

【讨论】:

    【解决方案2】:

    您可以使用 github 页面获取。您不需要代理或其他任何东西。 请参考sample-repo。在文档中,您会找到对 github api 的获取调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-20
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 2016-02-08
      • 2021-09-23
      相关资源
      最近更新 更多