19

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"
        })
    }
});
Ehsan Nissar
  • 643
  • 2
  • 13
  • 35

2 Answers2

25

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"
            })
        }
}
    });
Chaitanya
  • 847
  • 1
  • 8
  • 15
  • can you edit my cloud function because as i said i am not sure where do i need to edit my code – Ehsan Nissar Aug 02 '19 at 13:12
  • I've added portion of code into your cloud function. Once check and let me know if any error as I didn't tested it. – Chaitanya Aug 02 '19 at 13:26
  • do we need to remove it when requests are sent from a production url ? – Damien Romito Oct 02 '19 at 16:05
  • @DamienRomito browser will make `OPTIONS` call if your client app and server app running in the different domains. If you gonna host both client and server app in the same domain, then no need to handle `OPTIONS` call as browser itself won't make that call – Chaitanya Oct 03 '19 at 04:44
0

On server side try this: npm install cors. Then const cors = require('cors')({origin: true}); Maybe this link will help you: Enabling CORS in Cloud Functions for Firebase Also you can disable CORS rules in browser using plugin, for example in crome: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Yurii
  • 171
  • 2
  • 17