Home >Web Front-end >JS Tutorial >How to Enable CORS in Firebase Cloud Functions (v1 & v2)?

How to Enable CORS in Firebase Cloud Functions (v1 & v2)?

DDD
DDDOriginal
2024-12-09 14:06:11580browse

How to Enable CORS in Firebase Cloud Functions (v1 & v2)?

Enabling CORS in Cloud Functions for Firebase

When attempting to call a Cloud Function from an AJAX request, developers often encounter "No 'Access-Control-Allow-Origin'" errors. This issue stems from cross-origin blocking, which prohibits access to functions from an origin other than the one that created them.

To resolve this issue, Firebase provides options for enabling CORS in both Cloud Functions versions 1 and 2.

Cloud Functions v2

For Cloud Functions v2, CORS can be enabled directly within the function definition. The following code demonstrates how to achieve this:

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

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

Cloud Functions v1

For Cloud Functions v1, Firebase provides sample functions that demonstrate CORS usage. These samples showcase alternative approaches to working with CORS.

One approach involves importing CORS as follows:

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

The general form of a function using this approach would be similar to:

exports.fn = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    // function body using req and res provided by cors
  });
});

By adopting these methods, developers can seamlessly enable CORS in Cloud Functions, allowing their functions to be accessible from external origins.

The above is the detailed content of How to Enable CORS in Firebase Cloud Functions (v1 & v2)?. 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