import { onRequest } from "firebase-functions/v2/https";
import * as logger from "firebase-functions/logger";
import * as cors from "cors";
const corsHandler = cors({ origin: true });
export const helloWorld = onRequest((request, response) => {
corsHandler(request, response, () => {
logger.info("Hello logs!", { structuredData: true });
response.send("Hello from Firebase!");
});
});
And I also tried
import { onRequest } from "firebase-functions/v2/https";
import * as logger from "firebase-functions/logger";
export const helloWorld = onRequest({ cors: true }, (request, response) => {
logger.info("Hello logs!", { structuredData: true });
response.send("Hello from Firebase!");
});
And, I still get an error
Access to fetch at 'https://asdfeasdfsadf/hellowWorld' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am calling the function
const functions = getFunctions();
const hellowWorld = httpsCallable(functions, "helloWorld");
hellowWorld({})
.then((result) => {
// Read result of the Cloud Function.
/** @type {any} */
const data = result.data;
console.log(data);
})
.catch((error) => {
// Getting the Error details.
const code = error.code;
const message = error.message;
const details = error.details;
// ...
});
Why am I keep getting cors
error?
An onRequest function is not the same as a callable function and they are not compatible with each other. You should familiarize yourself with their differences.
You should use httpsCallable
only to invoke onCall
type functions (not onRequest
). onCall
functions handle cors automatically, so if you switch to onCall instead of onRequest, it should work as expected. If you actually want a normal HTTP onRequest function instead, and not a callable function at all, then don't use httpsCallable on the frontend to invoke it - just use a normal HTTP client library instead, such as the standard javascript fetch API.