Stiño
Stiño

Reputation: 2853

Firebase Cloud Functions: Cors examples don't work

I'm trying to call a simple helloWorld firebase cloud function from my local web app. The logs in Firebase return a status code 200 when I call the function but I face CORS issues. I have already implemented CORS solution steps suggested by Firebase (see index.js code below) but this does not work in my case. Is there anything else I can try to solve this issue?

When I call the endpoint in the browser it returns:

 {"headers":{"Access-Control-Allow-Origin":"*"},"body":{"message":"Hello world"}}

But when I fetch from my app:

 fetch(endpoint, {
   method: "GET", 
   mode: "no-cors", 
   cache: "no-cache", 
   credentials: "same-origin", 
   headers: {
     "Content-Type": "application/json; charset=utf-8",
   },
   redirect: "follow", 
   referrer: "no-referrer", 
 }).then(response => {
   console.log("response", response)
 });

I get an opaque response:

enter image description here

My index.js file:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const cors = require('cors')({origin: true});
const app = express();

app.use(cors);
app.get('/', (req, res) => {
  res.set('Access-Control-Allow-Origin', '*')
  res.status(200).send({
    headers: {'Access-Control-Allow-Origin': '*'},
    body: { "message": "Hello world"},
  });
});

exports.helloWorld = functions.https.onRequest(app);

Upvotes: 1

Views: 110

Answers (1)

Carol Skelly
Carol Skelly

Reputation: 362380

Use mode: cors instead of mode: no-cors on the fetch.

Upvotes: 2

Related Questions