简体   繁体   中英

Getting No “Access-Control-Allow-Origin” Error when posting from firebase hosting to firebase cloud functions

I have a post function from firebase cloud functions, then, when I send the post request from my react app (hosted on firebase hosting), the console returns the following error:

Access to XMLHttpRequest at 'https://asia-east2-example.cloudfunctions.net/api/something' from origin 'https://example.firebaseapp.com' 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.

and also this:

POST https://asia-east2-example.cloudfunctions.net/api/something net::ERR_FAILED

I have read some of the other stackoverflow questions but I don't really understand them.

index.js (firebase functions)

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

const config = {
  apiKey: "XXXXXXXXXXXXXXXXXXX",
  authDomain: "xampleee.firebaseapp.com",
  databaseURL: "https://example.firebaseio.com",
  projectId: "example",
  storageBucket: "example.appspot.com",
  messagingSenderId: "1111111111111",
  appId: "1:1111111111111:web:1111111111111",
  measurementId: "X-XXXXXXXXXXX",
};

admin.initializeApp();
firebase.initializeApp(config);

...

app.post("/response", (req, res) => {
  // cors(req, res, () => {
  let name = "";
  if (req.body.name !== null && req.body.name !== undefined) {
    name = req.body.name;
  } else {
    name = "anonymous";
  }

  const newResponse = {
    answer: req.body.answer,
    answerNames: req.body.answerNames,
    user: name,
    dateAnswered: new Date().toISOString(),
  };

  admin
    .firestore()
    .collection("Responses")
    .add(newResponse)
    .then((doc) => {
      const resResponse = newResponse;
      resResponse.responseId = doc.id;
      res.json(resResponse);
    })
    .catch((err) => {
      res.status(500).json({
        error: "Something went wrong",
      });
      console.error(err);
    });
  // });
});

...

exports.api = functions.region("asia-east2").https.onRequest(app);

firebase.json

{
  "hosting": {
    "public": "build",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "headers": [
      {
        "source": "**",
        "headers": [
          {
            "key": "Access-Control-Allow-Origin",
            "value": "*"
          }
        ]
      }
    ]
  }
}

package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "8"
  },
  "dependencies": {
    "firebase": "^7.15.0",
    "firebase-admin": "^8.10.0",
    "firebase-functions": "^3.7.0"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.2.0"
  },
  "private": true,
  "homepage": "./",
  "proxy": "https://asia-east2-example.cloudfunctions.net/api"
}

I will be happy to clarify anything unclear, and also to include more code as per requested. Thanks in advance.

You need to enable CORS for your Cloud Functions.

You should import the npm cors library like this:

const cors = require("cors");

Then, you also need to make your express app use it with:

app.use(cors());

See the npm cors library reference for further cors configuration options

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