【问题标题】:ReferenceError : XMLHttpRequest is not defined when running my angular 6 universal appReferenceError:运行我的 Angular 6 通用应用程序时未定义 XMLHttpRequest
【发布时间】:2019-03-24 07:46:07
【问题描述】:

我制作了一个 Angular 6 项目,它具有依赖项 Angularfire2 。 我正在使用 firestore 和 firebase 存储。 我已将我的应用程序转换为 Angular Universal,当我运行 server.js 时,它说正在收听 localhost:4000 但只要我用 localhost:4200 打开浏览器,终端就会显示以下错误:

ReferenceError: XMLHttpRequest is not defined

here is the snippet of the error

【问题讨论】:

  • 你好,杰尼特!欢迎来到 StackOverflow!请考虑发布MCVE (Minimal, Complete and Verifiable Example) 以便我们为您提供帮助,而不是发布控制台输出的图像,如果没有重现您的案例所需的代码,这对任何人都没有任何帮助。

标签: angular firebase angularfire2


【解决方案1】:

安装这些依赖项:

npm install --save-dev ws xmlhttprequest

然后将其添加到您的 server.ts 文件中

(global as any).WebSocket = require('ws');
(global as any).XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

如果您在使用 Firebase 时遇到任何其他 SSR 问题,请check if this article already covers it

来源:

【讨论】:

  • 我在尝试角度的 ssr 模式(不是 firebase)时遇到了同样的问题。此解决方案导致ERR_EMPTY_RESPONSE。没有负载。服务器没有响应。
【解决方案2】:

如果有人遇到同样的问题,我的解决方案是确保我没有在我的子模块中导入 HttpClientModule。一旦它已经导入到主 AppModule 中,错误就消失了。

这是给我解决方案的链接 https://www.thecodecampus.de/blog/angular-universal-xmlhttprequest-not-defined-httpclient/

【讨论】:

    【解决方案3】:

    为了将来参考,使用xmlhttprequest 对我不起作用,所以我不得不像这样使用xhr2

    1. npm install ws xhr2 bufferutil utf-8-validate -D
    2. 然后将wsxhr2 添加到server.ts

    (global as any).WebSocket = require('ws');
    (global as any).XMLHttpRequest = require('xhr2');

    【讨论】:

    • 我在尝试角度的 ssr 模式(不是 firebase)时遇到了同样的问题。此解决方案导致ERR_EMPTY_RESPONSE。没有负载。服务器没有响应。
    【解决方案4】:

    您必须安装@angular/platform-server 并导入ServerModule。它提供了 DOM、XMLHttpRequest 和其他不依赖浏览器的低级功能的服务器实现。

    欲了解更多信息,请参阅the universal guide

    【讨论】:

    • @jayneetporwal 你应该分享你的代码,以及你是如何让它“通用”的,因为看起来问题就在那里
    • 如何告诉 Angular 使用ServerModule 提供的那些实现。你能提供一些样品吗?
    猜你喜欢
    • 2017-11-08
    • 2018-12-09
    • 1970-01-01
    • 2019-12-31
    • 2019-01-27
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    相关资源
    最近更新 更多