angular / angularfire

Angular + Firebase = ❤️
https://firebaseopensource.com/projects/angular/angularfire2
MIT License
7.67k stars 2.19k forks source link

error calling Firebase Functions from Angular7: Response is not valid JSON object #2048

Closed bkalinovsky closed 5 years ago

bkalinovsky commented 5 years ago

I am try use firebase functions in angular application. I use angularfire2 library In result:

{err: Error: Response is not valid JSON object. at new HttpsErrorImpl (http://localhost:4200/vendor.j…}

source function:

const functions = require('firebase-functions');

const cors = require('cors')({
    origin: true
  });

exports.helloWorld = functions.https.onRequest((request, response) => {
    cors(request, response, () => {
        response.send('Hello from Firebase!');
    });

});

source angular app:

import { Component, OnInit } from '@angular/core';
import { AngularFireFunctions } from 'angularfire2/functions';
import { Observable } from 'rxjs';
import { first } from 'rxjs/operators';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  message: Observable<string>;
  message2: string;

  constructor(private fns: AngularFireFunctions) {
  }

  ngOnInit() {
  }

  getfsf() {

    this.fns.httpsCallable('helloWorld')({ text: 'Some Request Data' })
      .pipe(first())
      .subscribe(resp => {
        console.log({ resp });
      }, err => {
        console.error({ err });
      });

  }
}
samjacobson commented 5 years ago

Use functions.https.onCall (https://firebase.google.com/docs/reference/functions/functions.https#.onCall). AngularFire is using the underlying firebase client SDK, and for functions called by the client this is what it is expecting.

When using onCall (instead of onRequest) you don't need to do CORS yourself either.