Firebase + Node.js: Error: The XMLHttpRequest comp

2020-08-10 19:08发布

问题:

Firebase + Node.js

On iOS:

  1. Installed Node.js
  2. npm install firebase --save
  3. node test.js

Where test.js is a very simply script to connect to Firebase:

var firebase = require("firebase/app");
require("firebase/auth");

var config = {
   ...
};

var app = firebase.initializeApp(config); // Works fine
firebase.auth().signInWithEmailAndPassword(…); // Throws error

The error thrown is

Error: The XMLHttpRequest compatibility library was not found.

What am I overlooking? Thanks.

回答1:

I had the same issue by using Angularfire2 with Universal Server Side rendering. I've solved it by adding the xmlhttprequest to my server.js file.

Just like this:

npm install xmlhttprequest --save

and adding it like:

global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

or

global['XMLHttpRequest'] = require('xmlhttprequest').XMLHttpRequest;

Maybe it helps someone!



回答2:

Mmmhhh. Interesting. By changing the multiple 'require' lines (taken from the Firebase docs) into a single:

var firebase = require("firebase");

It started working just fine.



回答3:

For Firebase Server side rendering to work properly you need to install:

  • npm i xmlhttprequest ws -s
  • npm i bufferutil utf-8-validate -s

Then on the server.ts file(found at the root folder) add:

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

Read on more on this tutorial: here



回答4:

I finally got it after 2 days of trying hard!

You should not put the firebase code in the constructor. Move it the componentDidMount() method. And move the functions above the constructor.

Hope this helps someone.