Enable Cors in Firebase Cloud Function

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"
            })
        }
}
    });