Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable Cors in Firebase Cloud Function

I have written some cloud functions and deployed them now i am trying to hit those APIs using my Angular application but i am getting this error

Access to XMLHttpRequest at 'xxxxxxxxxxxxxxxxxxxxxxxx' from origin 'http://localhost:4200' 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.

I know i have to enable cors in my cloud function but i have never done that before so would be awesome if you guys could tell me how to do that? I did checked this thread but i am a little bit confused as to where i need to initialize the cors and do i need to install its dependency too and where do i need to enable it in my cloud function? Here is my cloud function

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


const admin = require("firebase-admin");

const bodyParser = require("body-parser");


admin.initializeApp();

const db = admin.firestore();

const usersCollection = db.collection("users");

exports.addUser = functions.https.onRequest((req, res) => {
    if (req.body.username != null && req.body.firstname != null && req.body.lastname != null && req.body.addr1 != null && req.body.addr2 != null || req.body.username != undefined && req.body.firstname != undefined && req.body.lastname != undefined && req.body.addr1 != undefined && req.body.addr2 != undefined ) {
        let docId = Math.floor(Math.random() * (99999 - 00000));
        let newUser = {
            "username": req.body.name,
            "firstname": req.body.firstname,
            "lastname": req.body.lastname,
            "addr1": req.body.addr1,
            "addr2": req.body.addr2,
        }
        usersCollection.add(newUser).then(snapshot => {
            res.send(200, {
                "message": "User was successfully created"
            })
        });


    } else {
        res.send(400, {
            "message": "All fields are required"
        })
    }
});
like image 344
Ehsan Nissar Avatar asked Aug 02 '19 12:08

Ehsan Nissar


1 Answers

There are two ways to solve this

  1. Using externally library to handle OPTIONS call

cors

  1. Handle OPTIONS call manually

Get request Method from headers

Check if the method is OPTIONS

Resolve the API with 200 status code.

 exports.addUser = functions.https.onRequest((req, res) => {

res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS');
res.set('Access-Control-Allow-Headers', '*');

 if (req.method === 'OPTIONS') {
   res.end();
}

else{
        if (req.body.username != null && req.body.firstname != null && req.body.lastname != null && req.body.addr1 != null && req.body.addr2 != null || req.body.username != undefined && req.body.firstname != undefined && req.body.lastname != undefined && req.body.addr1 != undefined && req.body.addr2 != undefined ) {
            let docId = Math.floor(Math.random() * (99999 - 00000));
            let newUser = {
                "username": req.body.name,
                "firstname": req.body.firstname,
                "lastname": req.body.lastname,
                "addr1": req.body.addr1,
                "addr2": req.body.addr2,
            }
            usersCollection.add(newUser).then(snapshot => {
                res.send(200, {
                    "message": "User was successfully created"
                })
            });


        } else {
            res.send(400, {
                "message": "All fields are required"
            })
        }
}
    });
like image 176
Chaitanya Avatar answered Oct 29 '22 09:10

Chaitanya