The following is the client-side code to call the cloud function:
// add a new post
addPostForm.addEventListener('click', (e) => {
e.preventDefault();
const addPost = httpsCallable(functions, 'addPost');
addPost({
title: addPostForm.postTitle.value,
description: addPostForm.postDescription.value,
})
.then(() => {
addPostForm.reset(),
addPostModal.classList.remove('open');
addPostForm.querySelector('.error').textContent = '';
})
.catch(error => {
addPostForm.querySelector('.error').textContent = error.message;
})
});
The cloud function:
exports.addPost = functions.https.onCall((data, context) => {
if(!context.auth){
throw new functions.https.HttpsError(
'unauthenticated',
'only authenticated users can post'
);
}
if(data.text.length > 140){
throw new functions.https.HttpsError(
'invalid-argument',
'description must be no more than 140 characters long'
);
}
return admin.firestore().collection('Posts').add({
title: data.title,
description: data.description,
likes: '',
bookmarks: '',
});
});
Firebase Setup:
import { initializeApp, getApp } from "firebase/app";
import { getAuth, connectAuthEmulator } from "firebase/auth";
import { getStorage, connectStorageEmulator } from "firebase/storage";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
import { getFunctions, connectFunctionsEmulator } from "firebase/functions";
const firebaseConfig = {
"config"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
const storage = getStorage(app);
const functions = getFunctions(getApp(), app);
if (window.location.hostname.includes("localhost")) {
connectAuthEmulator(auth, "http://localhost:9099");
connectFirestoreEmulator(db, 'localhost', 8080);
connectStorageEmulator(storage, 'localhost', 9199);
connectFunctionsEmulator(functions, "localhost", 5001);
}
export { auth, db, storage, functions };
Error Access to fetch at 'http://localhost:5001/app/object/addPost' From origin 'http://localhost:5173' 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.
What's the problem here? Will I need to set up firebase admin to grant access rights, and if I turn CORS off in the browser will that present a security issue on production?