简体   繁体   中英

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

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

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:

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/

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM