Home >Web Front-end >JS Tutorial >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:
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!