ReferenceError : XMLHttpRequest is not defined when running my angular 6 universal app

落花浮王杯 提交于 2020-05-29 07:44:31

问题


I have made a Angular 6 project with dependency Angularfire2 . I am using firestore and firebase storage. I have converted my app to angular universal and when i run server.js it says listening on localhost:4000 but as soon as i open the browser with localhost:4200 the terminal shows the following error:

ReferenceError: XMLHttpRequest is not defined

here is the snippet of the error


回答1:


Install these dependencies:

npm install --save-dev ws xmlhttprequest

Then add this to your server.ts file

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

If you run into any other issue with SSR by using Firebase, check if this article already covers it.

Sources:

  • https://angularfirebase.com/lessons/server-side-rendering-firebase-angular-universal/
  • https://angularfirebase.com/snippets/angular-6-universal-simple-guide/



回答2:


If anyone gets the same problem, the solution for me was to make sure that I did not import the HttpClientModule in my child modules. Once it was already imported in the main AppModule, the error went away.

Here is a link that gave me the solution https://www.thecodecampus.de/blog/angular-universal-xmlhttprequest-not-defined-httpclient/




回答3:


For future reference using xmlhttprequest didn't work me so I had to use xhr2 like so:

  1. npm install ws xhr2 bufferutil utf-8-validate -D
  2. And then adding both ws and xhr2 to server.ts

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




回答4:


You have to install the @angular/platform-server and import the ServerModule. That provides server implementations of the DOM, XMLHttpRequest, and other low-level features that don't rely on a browser.

For more information see the universal guide



来源:https://stackoverflow.com/questions/52891992/referenceerror-xmlhttprequest-is-not-defined-when-running-my-angular-6-univers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!