Firestore and CORS

1,478 views
Skip to first unread message

Arnaud Deman

unread,
Mar 22, 2018, 8:03:08 PM3/22/18
to Firebase Google Group
Hi,

I am trying to use firestore (which is new for me) in an Angular 5 app but I am facing a CORS error and I am a little bit stucked.

A service in my Angular App makes an http post to a firebase function written in nodejs and epress to make a record into firestore.
I do not have a very thorough knowledge of cors and this is probably one of the sources of my problem.

The function use express and this is the relevant code :

initialization of firebase

import * as functions from 'firebase-functions';
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

Initialization of express :

import * as express from 'express';
import * as cors from 'cors';
const twitterApp = express();
twitterApp.use(cors({ origin: true }));


The code in the express post handler,  used  to make the record into firestore :

private _db = admin.firestore();
...
post(req, res, next) {
...
const docRef = this._db.collection('tweet').doc(postedTweetVO.tweetId);
return docRef.set(postedTweetVO).then((registeredTweet) => {
...
}).catch(error => {
...
});

And this is the error in the browser where the Angular app is executed :

admin-document:1 Failed to load https://us-central1-corpussystem.cloudfunctions.net/twitter/twt: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.


If I change the few lines of code above to make the record into the realtime database instead  of firestore it works fine :
post(req, res, next) {
...
return admin.database().ref('/tweet').push(postedTweetVO).then((snapshot) => {
...
}).catch(error => {
...
})

I can interact with firestore from my laptop with nodejs scripts whihout any trouble.
I have subscribed the flame plan so it is probably not a problem of outbound netorking.

Thanks for your help,
regards,
Arnaud.

Arnaud Deman

unread,
Mar 23, 2018, 10:03:20 AM3/23/18
to Firebase Google Group
Hi,

I found the problem, and the CORS error message was not relevant.
The problem was due to the fact I tryed to write a Object and not a plain javascript object and because of that  the function crashed.

I replaced :

const postedTweetVO = new PostedTweetVO();
postedTweetVO.userId = data.user.id_str;
postedTweetVO.tweetId = data.id_str;
postedTweetVO.timestamp = timestamp;

const docRef = this._db.collection('tweet').doc(postedTweetVO.tweetId);
return docRef.set(postedTweetVO).then((registeredTweet) => { (...)

By :

const postedTweetVO = {
userId: data.user.id_str,
tweetId: data.id_str,
timestamp: timestamp
};

const docRef = this._db.collection('tweet').doc(postedTweetVO.tweetId);
return docRef.set(postedTweetVO).then((registeredTweet) => { (...)

Regards,
Arnaud.
Reply all
Reply to author
Forward
0 new messages