0

I'm trying to deploy a firebase cloud function with cors but it doesn't work. This is my code bellow, can someone help me with this ?

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as cors from 'cors'

admin.initializeApp()

const corsHandler = cors({origin: true})

export const getUser = functions.https.onRequest((request, response) => {

    corsHandler(request, response, () => {})

    admin.firestore().doc("profiles/T0XCPHPkrJM4I10okb9KSHyukqn1").get()
    .then(snapshot => {
        const data = snapshot.data()
        console.log(data)
        response.send(data)
    })
    .catch(error => {
        console.log(error)
        response.status(500).send(error)
    })

})
dhammani
  • 141
  • 1
  • 14
  • What exactly is the error that you are receiving? – caro Jan 09 '19 at 02:15
  • 2
    Also, https://stackoverflow.com/questions/42755131/enabling-cors-in-cloud-functions-for-firebase?rq=1 may be helpful - it looks like their problem was similar to yours. – caro Jan 09 '19 at 02:16
  • Possible duplicate of [Enabling CORS in Cloud Functions for Firebase](https://stackoverflow.com/questions/42755131/enabling-cors-in-cloud-functions-for-firebase) – Dennis Alund Jan 09 '19 at 02:45
  • I already checked it, the solution I used is on this post but it doesn't work. Oliver Dixon commented the response for Typescript, he said that "Solution will make you lose logging on cloud functions (very bad)" – dhammani Jan 09 '19 at 03:16
  • did you call initializeApp properly or did you remove the rest of your code for demoing, didn't you have to reference serviceAccount.json and all that stuff. – Zhang Bruce Jan 09 '19 at 03:41
  • This is all the code – dhammani Jan 09 '19 at 04:56

1 Answers1

1

The following should work. You have to include the code of your asynchronous Firebase call inside the function.

import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as cors from 'cors'

admin.initializeApp()

const corsHandler = cors({origin: true})

export const getUser = functions.https.onRequest((request, response) => {

    corsHandler(request, response, () => {

        admin.firestore().doc("profiles/T0XCPHPkrJM4I10okb9KSHyukqn1").get()
        .then(snapshot => {
            const data = snapshot.data()
            console.log(data)
            response.send(data)
        })
        .catch(error => {
            console.log(error)
          response.status(500).send(error)
        })

    })

})
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121