代码之家  ›  专栏  ›  技术社区  ›  MetaColon

盖茨比XMLHttpRequest

  •  0
  • MetaColon  · 技术社区  · 7 年前

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


    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();
    

    我已经围绕它开发了一些代码,它工作得很好,但是当我想部署它并运行它时 盖茨比大厦 ,我得到:

    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 ,但根本不知道从哪里开始,因为这是我的第一个盖茨比项目,事实上也是我的第一个更大的JS项目。

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

    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
    

    所以,即使有其他人已经有了类似的问题,我还是会感谢有一个具体的解决方案来解决我的问题。

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

    0 回复  |  直到 7 年前
        1
  •  0
  •   Ammar    7 年前

    它在生成html页面时失败,因为 XMLHttpRequest 那时候还没有定义。使用前 XMLHttpRequest 您可以检查它是否已定义。

    if(typeof XMLHttpRequest !== "undefined")
    

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