【问题标题】:Gatsby XMLHttpRequest盖茨比 XMLHttpRequest
【发布时间】:2019-08-07 02:40:27
【问题描述】:

简而言之:我想在 Gatsby 中使用 XMLHttpRequest,它在开发模式下工作,但在生产 (gatsby build) 模式下失败,我无法修复。


更多信息:我想访问一个 API(准确地说是 GitHub API)。因此我发出这样的 HTTP 请求:

const repoRequest = new XMLHttpRequest();
const repoUrl = "https://api.github.com/user/repos?visibility=all?type=all";
repoRequest.open("GET", repoUrl);
repoRequest.setRequestHeader("Authorization", "token <here would be my token>");
repoRequest.send();

我围绕它开发了一些代码,它运行良好,但是当我想部署它并运行 gatsby build 时,我得到了:

error Building static HTML failed

See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html

  69 | let age = ((today - birthday) / 1000 / 60 / 60 / 24 / 365).toFixed(1);
  70 |
> 71 | const repoRequest = new XMLHttpRequest();
     |                     ^
  72 | const repoUrl = "https://api.github.com/user/repos?visibility=all?type=all";
  73 | repoRequest.open("GET", repoUrl);
  74 | repoRequest.setRequestHeader("Authorization", "token <here would be my token>");


  WebpackError: ReferenceError: XMLHttpRequest is not defined

按照here 的建议,我尝试使用 i18n,但根本不知道从哪里开始,因为这是我的第一个 Gatsby 项目,实际上也是我的第一个更大的 JS 项目。

更复杂的是,我使用了this starter(我的项目看起来基本上还是一样,所以你可以对我的代码有一个很好的印象),这似乎不在默认的 Gatsby 布局中。

我正在使用带有 linux 子系统 (Ubuntu) 的 Windows 10,我在其中运行 npm、Gatsby、...,同时我在 Windows 中编辑 IntelliJ 中的代码 - 我认为这无关紧要,但是一个永远不知道。这是我运行sudo gatsby info时得到的:

  System:
    OS: Linux 4.4 Ubuntu 16.04.6 LTS (Xenial Xerus)
    CPU: (16) x64 AMD Ryzen 7 1700 Eight-Core Processor
    Shell: 4.3.48 - /bin/bash
  Binaries:
    Node: 11.11.0 - /usr/bin/node
    npm: 6.9.0 - /usr/bin/npm
  Languages:
    Python: 2.7.12 - /usr/bin/python
  npmPackages:
    gatsby: ^2.1.35 => 2.1.35
    gatsby-cli: ^2.4.16 => 2.4.16
    gatsby-image: ^2.0.31 => 2.0.33
    gatsby-plugin-debug-build: ^1.0.0 => 1.0.0
    gatsby-plugin-google-analytics: ^2.0.16 => 2.0.17
    gatsby-plugin-manifest: ^2.0.22 => 2.0.24
    gatsby-plugin-netlify: ^2.0.11 => 2.0.12
    gatsby-plugin-offline: ^2.0.24 => 2.0.25
    gatsby-plugin-page-load-delay: ^0.1.2 => 0.1.2
    gatsby-plugin-react-helmet: ^3.0.8 => 3.0.9
    gatsby-plugin-sharp: ^2.0.25 => 2.0.28
    gatsby-plugin-styled-components: ^3.0.6 => 3.0.7
    gatsby-source-filesystem: ^2.0.23 => 2.0.24
    gatsby-transformer-sharp: ^2.1.15 => 2.1.17

因此,即使其他人可能已经遇到了类似的问题,但我会感谢为我的问题提供具体的解决方案。

我实际上尝试过简单地部署开发版本,但这似乎并不那么容易(在部署公用文件夹时,就像我对生产版本所做的那样,我只是得到一个空页面)。因此,如果您知道我如何部署开发版本,这实际上也会对我有很大帮助。

【问题讨论】:

  • 虽然我没有找到解决方案,但我确实找到了使用 graphql 的“解决方法”,这可能是执行此操作的首选方法。

标签: javascript node.js reactjs xmlhttprequest gatsby


【解决方案1】:

它在构建 html 页面期间失败,因为当时没有定义 XMLHttpRequest。在使用 XMLHttpRequest 之前,您可以检查它是否已定义。

if(typeof XMLHttpRequest !== "undefined")

看到这个 https://www.gatsbyjs.org/docs/debugging-html-builds/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-16
    • 2021-12-14
    • 2022-08-19
    • 2021-07-30
    • 2020-12-02
    • 2021-07-12
    • 2019-04-02
    • 2021-08-22
    相关资源
    最近更新 更多