Ad

Firebase Cloud Function Executing Twice When Triggered Over HTTP

I'm trying to integrate Firebase Cloud Functions into my Ionic 3 App. The goal is to create a cloud function that will create a user using the admin SDK.

However, when triggering this function over HTTP it will execute twice only when passing data to it, if I just call the function with no data it executes once as intended.

Cloud Function Code:

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

exports.createUser = functions.https.onRequest((request, response) => {
  response.set('Access-Control-Allow-Origin', '*');
  response.set('Access-Control-Allow-Headers', 'Content-Type');
  console.log(request.body);
  response.status(200).send('Hello from Firebase!');
});

HTTP Request:

axios.post(functionURL, {
  data: 'some data'
})
.then(res => {
  console.log(res.data);
})
.catch(err => console.log(err));

The HTTP request above works as intended and I see "Hello from Firebase! " only once in the console, however when I look at the functions logs it's showing it's being executed twice.

enter image description here

I'm very new to Firebase Cloud Functions so any input or suggestions would be greatly appreciated!

Ad

Answer

Solved

Solution found here: Cloud Functions for Firebase triggering function on CORS preflight request

As I was sending the data as application/json it was triggering a CORS preflight request, which is exactly what was causing the function to execute twice when passing data.

To bypass this, I simply sent the data as a application/x-www-form-urlencoded string like this:

const dataStr = JSON.stringify(objectToPass);

axios({
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: `data=${dataStr}`
})

And then parse the body back into an object in the function like this:

const data = JSON.parse(request.body.data);
Ad
source: stackoverflow.com
Ad