3

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

Sunil Singh
  • 11,001
  • 2
  • 27
  • 48
jayneet porwal
  • 111
  • 1
  • 3
  • Hello, Jayneet! Welcome to StackOverflow! Please consider posting an [MCVE _(Minimal, Complete and Verifiable Example)_](https://stackoverflow.com/help/mcve) so that we could help you, instead of posting images of a console output which in no way helps anyone without the code required to reproduce your case. – Edric Oct 19 '18 at 12:34

4 Answers4

9

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:

michelepatrassi
  • 2,016
  • 18
  • 32
  • I've the same problem when trying ssr mode of angular (not firebase). this solution results in `ERR_EMPTY_RESPONSE`. nothing loads . server does not respond. – Shahryar Saljoughi May 18 '20 at 04:15
5

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/

David
  • 33,444
  • 11
  • 80
  • 118
0

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

Nadhir Falta
  • 5,047
  • 2
  • 21
  • 43
  • I've the same problem when trying ssr mode of angular (not firebase). this solution results in `ERR_EMPTY_RESPONSE`. nothing loads . server does not respond. – Shahryar Saljoughi May 18 '20 at 04:15
-1

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

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149