CORS Error when running App on Real Device

#1

Hi guys, Im using a firebase cloud function (code shown below) which basically updates the number of likes on a particular post (its for a social media app).

/* this cloud function is used to update the likes on a post
- it receives three parameters in the post body 
- and will update those respective fields in the post document (e.g number of likes)
*/

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

  const postId = JSON.parse(request.body).postId;
  const userId = JSON.parse(request.body).userId;
  const action = JSON.parse(request.body).action; // 'like' or 'unlike' 

  // from this data object we can get the value of all the fields in the document
  admin.firestore().collection("posts").doc(postId).get().then((data) => {

    // if likes counts = 0, then assume there are no likes 
    let likesCount = data.data().likesCount || 0;
    // likewise if there are no likes, then assign an empty array
    let likes = data.data().likes || [];

    let updateData = {};

    if(action == "like")
    {
      updateData["likesCount"] = ++likesCount;
      updateData[`likes.${userId}`] = true;
    } 
    else 
    {
      updateData["likesCount"] = --likesCount;
      updateData[`likes.${userId}`] = false;
    }

    admin.firestore().collection("posts").doc(postId).update(updateData).then(() => {
      response.status(200).send("Done")
    }).catch((err) => {
      response.status(err.code).send(err.message);
    })

  }).catch((err) => {
    response.status(err.code).send(err.message);
  })

})

When the app is running and the ‘like’ button is pressed, I get this console error…

Please help, I cant seem to find many answers online, and the solutions I do find don’t seem to work for me. Many thanks! :slight_smile:

#2

Are you using Cordova?

Add this to the config.xml:

access origin="*"

And this plugin: cordova-plugin-whitelist

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/index.html

1 Like
#3

Thanks for the reply Bandito,

Yes I am using Cordova, and have installed the plugin you mentioned.

I also seem to already have that line of code in the file… as shown below…

image

Below I have included a screenshot of the console log for error info. The weird thing is that the likes actually do get updated in Firebase, but I still get an error message on the console due to CORS…

#4

Oh I think that happened to me. I think it was an Angular thing, I think I fixed it because my server wasn’t accepting any connections because I didn’t include the local host/IP.

But it was a server issue not an Ionic. Check that the GET function have the correct headers. That was I think I did the fix the issues.

I think for Firebase all you need is the API key

#5

I found the solution which worked for me bandito, great article describing the solution here…

So here is my updated cloud function for anyone experiencing similar issues…

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

admin.initializeApp(functions.config().firebase);

const cors = require('cors')({
  origin: true
});

/* this cloud function is used to update the likes on a post
- it receives three parameters in the post body 
- and will update those respective fields in the post document (e.g number of likes)
- check out this link for work around for CORS error...
- https://ilikekillnerds.com/2017/05/enabling-cors-middleware-firebase-cloud-functions/
*/
exports.updateLikesCount = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
     
      console.log(req.body);
    
      const postId = JSON.parse(req.body).postId;
      const userId = JSON.parse(req.body).userId;
      const action = JSON.parse(req.body).action; // 'like' or 'unlike' 
    
      // from this data object we can get the value of all the fields in the document
      admin.firestore().collection("posts").doc(postId).get().then((data) => {
    
        // if likes counts = 0, then assume there are no likes 
        let likesCount = data.data().likesCount || 0;
        // likewise if there are no likes, then assign an empty array
        let likes = data.data().likes || [];
    
        let updateData = {};
    
        if(action == "like")
        {
          updateData["likesCount"] = ++likesCount;
          updateData[`likes.${userId}`] = true;
        } 
        else 
        {
          updateData["likesCount"] = --likesCount;
          updateData[`likes.${userId}`] = false;
        }
    
        admin.firestore().collection("posts").doc(postId).update(updateData).then(() => {
          res.status(200).send("Done")
        }).catch((err) => {
          res.status(err.code).send(err.message);
        })
    
      }).catch((err) => {
        res.status(err.code).send(err.message);
      })
    
    })
  });

Thanks for your help! :slight_smile:

1 Like