Home >Web Front-end >JS Tutorial >How to Enable CORS for Firebase Cloud Functions?

How to Enable CORS for Firebase Cloud Functions?

DDD
DDDOriginal
2024-12-03 03:33:09131browse

How to Enable CORS for Firebase Cloud Functions?

Enabling CORS for Cloud Functions for Firebase

When attempting to access a Cloud Function for Firebase using an AJAX request, users may encounter the "No 'Access-Control-Allow-Origin'" error. This occurs due to the lack of CORS (Cross-Origin Resource Sharing) configuration. To rectify this issue, CORS must be enabled within the function.

Solution for Cloud Functions v2:

Cloud Functions v2 provides a straightforward solution by incorporating CORS into the function definition:

const { onRequest } = require("firebase-functions/v2/https");

exports.sayHello = onRequest(
  { cors: true },
  (req, res) => {
    res.status(200).send("Hello world!");
  }
);

Solution for Cloud Functions v1:

For Cloud Functions v1, two sample functions provided by the Firebase team demonstrate CORS handling. The second sample employs a different method:

const cors = require("cors")({ origin: true });

exports.fn = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    // Implement the function body here using the provided req and res from CORS
  });
});

Additional Notes:

  • If the function returns a 500 error code, Axios/jQuery will retry depending on the configuration. Change the status code to 200.
  • Ensure the endpoint URL has the expected scheme (i.e. https://), matching the Origin header in the request.

The above is the detailed content of How to Enable CORS for Firebase Cloud Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn