0

My Cloud Function is very similar to the example in the docs. It looks like this:

def states(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        All states in the database.
    """
    if request.method == 'OPTIONS':
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST',
            'Access-Control-Allow-Headers': '*'
        }
        return ('', 204, headers)

    # request_json = request.get_json()
    headers = {
        'Access-Control-Allow-Origin': '*'
    }
    stmt = 'SELECT * FROM states'
    try:
        with db.connect() as conn:
            response = conn.execute(stmt)
        states_dict = {}
        for row in response:
            states_dict[row['name']] = str(row)
        print(states_dict)
        return ({'data': states_dict}, 200, headers)
    except Exception as e:
        error = 'Error: {}'.format(str(e))
        print(error)
        return (error, 200, headers)

When I test this function from the Cloud Functions UI, it returns results from Cloud SQL. However, when I call this from Vue using the following code, it gives me the following error in the console:

Access to fetch at 'https://<myappinfohere>.cloudfunctions.net/states' from origin 'https://myappinfohere.web.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Can someone help me debug why this is happening? I thought I handled CORS requests properly, and when I proxy the database locally I can even emulate the function and get it working locally. I cannot get it working in production, however.

EDIT: Here is the code on the client I'm using to access this function.

db.js

import firebase from 'firebase'

const config = {
  apiKey: REDACTED
  authDomain: REDACTED,
  databaseURL: REDACTED,
  projectId: REDACTED,
  storageBucket: REDACTED,
  messagingSenderId: REDACTED,
  appId: REDACTED,
  measurementId: REDACTED
}

const app = firebase.initializeApp(config)
// app.functions().useFunctionsEmulator('http://localhost:8081')
const db = firebase.firestore()
var gcFunc = firebase.functions().httpsCallable('states')

export {
  db,
  gcFunc,
  app
}

My Vuex code:

const fb = require('@/db.js')
...
fb.gcFunc({}).then((result) => {
   context.commit('setAllStates', Object.values(result.data))
})
Nick
  • 51
  • 1
  • 4
  • What's the result of `curl -I https://.cloudfunctions.net/states`? – Dustin Ingram Apr 27 '20 at 18:31
  • Thanks for the response! The output is: ``` HTTP/2 200 access-control-allow-origin: * content-type: application/json function-execution-id: p0uw6ue9yya2 x-cloud-trace-context: 09e9862d9cd199e61755edd0c990d58b;o=1 content-length: 2003 date: Mon, 27 Apr 2020 19:54:29 GMT server: Google Frontend ``` I see it has the `header access-control-allow-origin: *` – Nick Apr 27 '20 at 19:55
  • Sorry for the many edits, I can't seem to get the output to format properly as code. – Nick Apr 27 '20 at 19:59
  • @DustinIngram I added the js code I'm using to call the function to my original post. – Nick Apr 27 '20 at 20:39
  • 1
    Does this answer your question? https://stackoverflow.com/questions/40863417/cors-issue-with-vue-js – Dustin Ingram Apr 27 '20 at 23:26
  • Check [Firebase docs](https://firebase.google.com/docs/functions/http-events#using_existing_express_apps) and [this thread](https://stackoverflow.com/questions/42755131/enabling-cors-in-cloud-functions-for-firebase) – Emil Gi Apr 28 '20 at 07:55
  • After a ton of digging, I found the root of the problem (I believe). I can finally call my function from the client using axios, but I cannot import the function using firebase.functions() and then call it. Saying: `var gcFunc = app.functions().httpsCallable('states')` then calling gcFunc does not work, but sending a post request directly to the function works. I'd really love to be able to import my functions using firebase.functions() :( – Nick Apr 28 '20 at 20:05
  • I was originally following what was in this doc under "Call the function" but that doesn't seem to work with Cloud Functions not created through Firebase. https://firebase.google.com/docs/functions/callable – Nick Apr 28 '20 at 20:07
  • Is there an equivalent API on the Google Cloud side I can use instead of firebase.functions()? – Nick Apr 28 '20 at 20:07
  • I finally finally figured out the root cause. My Firebase project and Google Cloud project were not the same. I deleted my Firebase project and added it as an extension of Google Cloud and everything works! Thank you all for the help! Turns out it wasn't CORs related at all! – Nick Apr 28 '20 at 20:21

0 Answers0