简体   繁体   中英

Client side CORS error with cloud functions and Firebase

I am new to firebase and wanting to use their HTTP cloud functions. When I try to go to any endpoint (not using the emulator - eg https://us-central1-xxxxxxxx.cloudfunctions.net/app/api/admin/studio ) I am getting CORS errors.

Here is an example of my code. I have no security rules set currently (still in development). The code below works perfect when using the firebase emulator. Just not using the "live".cloudfunctions link.

Is there a permission or set up I am missing? This endpoint works if you access this directly via the browser or POSTMAN, just not from the react app.

An example of the error from the react app is:

Origin https://xxxxxxxxxxx is not allowed by Access-Control-Allow-Origin.
Fetch API cannot load https://us-central1-xxxxxxxx.cloudfunctions.net/app/api/admin/studio due to access control checks.

index.js

const functions = require("firebase-functions")
const express = require("express")
const app = express()
const cors = require("cors")({ origin: true })
app.use(cors)
const studio = require("./http/studio.js")
app.post("/api/admin/studio", studio.add)
exports.app = functions.https.onRequest(app)

db.js

const admin = require("firebase-admin")
admin.initializeApp()
module.exports = admin.firestore()

http/studio.js

const db = require("../db")
const error = require("./error")
exports.add = (req, res) => {
const { data } = req.body

if (!data) {
return error.no_data(res)
}

return db
.collection("data")
.doc("studio")
.update({ values: admin.firestore.FieldValue.arrayUnion(data) })
.then(res.status(200).send("Data updated successfully"))
.catch(err => error.updating(res, err))
}

I was able to fix with updating my index.js code to include a list of allowed origins.

const functions = require("firebase-functions")
const express = require("express")
const app = express()
const cors = require("cors")({ origin: true })


var allowedOrigins = ["https://domainone", "https://domaintwo"]
app.use(
  cors({
    origin: function(origin, callback) {
      if (!origin) return callback(null, true)
      if (allowedOrigins.indexOf(origin) === -1) {
        var msg = "The CORS policy for this site does not " + "allow access from the specified Origin."
        return callback(new Error(msg), false)
      }
      return callback(null, true)
    }
  })
)

const studio = require("./http/studio.js")
app.post("/api/admin/studio", studio.add)
exports.app = functions.https.onRequest(app)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM