Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

node.js - 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"
        })
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...