The ultimate guide to fixing CORS errors in Firebase cloud functions

Any suggestions on how to resolve CORS errors? I seem to be encountering a CORS error while testing a simple function, and I could really use some assistance.

         const functions = require('firebase-functions');
         const cors = require('cors')({ origin: true });
         import * as admin from 'firebase-admin';
         admin.initializeApp();

          exports.test = functions.https.onRequest((req, res) => {
            res.set('Access-Control-Allow-Origin', '*');
            res.set('Access-Control-Allow-Credentials', 'true');
            res.send("hello!!");
           });

          //when calling in .js file

           var test = firebase.functions().httpsCallable('test');
           test().then(function(result) {});

Answer №1

I have successfully tested API calls from various external domains and cloud functions, all of which are functioning without any issues.

If you provide some code examples, I can confirm their effectiveness.

Edit:

exports.fetchClientToken = functions.https.onRequest(
async (request, response) => {
const clientToken = await fetch("https://**/api/Token", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: "Username=*&Password=*&grant_type=password"
 });
 let tokenResponse = await clientToken.json();
 response.send(tokenResponse);
});

And the call is made as follows:

 const firebaseTokenMethod = await fetch("https://us-central1-*-1106.cloudfunctions.net/fetchClientToken",
 {
   method: "POST",
   headers: {
     "Content-Type": "application/json",
   }
 });

let token = await firebaseTokenMethod.json();

It is working perfectly for me without requiring any CORS imports or additional configurations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating default values in reactive() functions in Vue 3: A step-by-step guide

Currently, I am in the process of developing an application using Nuxt 3 and implementing the Composition API for handling async data. The specific scenario I am facing is this: I have a page that displays articles fetched from the database using useLazyFe ...

Tips for properly handling special characters in AJAX-loaded content?

During my ajax call, I encountered the following issue upon success: success: function(html){ var product_json = []; data=$(html); $(".product_json", data).each(function(){ product_json.push( jQuery.parseJSON( $(this).html() ) ); }); .... //code co ...

Update the second and third HTML inputs simultaneously as the first HTML input is being edited

Currently, I am displaying the values from a database table in an HTML + PHP table. My objective is to modify the quantity or price of an article and have the total value update automatically up to the specific row being edited. Additionally, I would like ...

For JavaScript to run, it must be included in the HTML document and invoked externally using the <script src=...> tag

When it comes to my JavaScript code, I've encountered an interesting scenario where it only seems to run properly when it is both included in the HTML file and called externally like so: <script type="text/javascript" src="{{ url_fo ...

JavaScript: specify parameters for function inputs

I'm curious about optimizing Javascript/Typescript functions arguments for clean code. To demonstrate, let's consider a basic example. Imagine I have a React component with a view property as props: <Grid view="Horizontal" /> ty ...

Why is the JSP command <%=%> getting overlooked within a Javascript statement located inside a taglib tag declaration?

Allow me to provide an example to make this concept easier to understand! The jsp file... <%@ taglib prefix ="jam" uri= "http://jam.tld" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1"%> <% ...

When scrolling the page, the Circle Mouse Follow feature will dynamically move with your cursor

Hey everyone! I'm currently working on implementing a mouse follow effect, but I'm facing an issue where the circle I've created moves along with the page when scrolling, instead of staying fixed to the mouse. Any suggestions or tips would b ...

Is there a way to stop the automatic triggering of the form submit action?

This form has an action event that triggers when a button is clicked. <form id="prefForm4" enctype="multipart/form-data" method="post" class="masters" action="/Preferences/Preferences/RISSave"> </form> There are two buttons in this form, ...

Enable users to modify the URL in the window.open() function

In the code snippet below, a new window opens when a user clicks on a button: $('.loginButton').click(function () { var strString = $("#medlineSearch").val() var strSearch = "http://google.com&query="; var url = strSearch + strSt ...

Updating a property on an object during iteration

Currently, I am in the process of developing a Single Page Application using Laravel on the backend and Vue.js. I have two arrays that are crucial to my project: The first array is accessArray: ["BIU","CEO","Finance","HRD","Group"] The second array is a ...

Display column on desktop, activate column on mobile device

What I have created is a layout with two columns, each taking up 50% of the desktop screen. When viewing on mobile, typically we would make the columns 100% to fit the smaller screen. However, in my case, I want the right column to be hidden on mobile and ...

Issue: React error message indicates that the .map() function is not recognized. The API response is in the form of an object, making

As a newcomer to REACT.JS, I am currently facing the challenge of extracting data from an API for my project. Utilizing "Axios" for sending the get request, I have encountered a situation where the response comes back as an array in one API and as an objec ...

Exploring Angular2: A Guide to Interpolating Expressions in Templates

Is it possible to interpolate different types of Javascript expressions? Along with displayed properties like object.property and short expressions such as {{1+1}}, what other valid Javascript expressions can be used for interpolation? ...

Combining CSS, jQuery, and HTML into a single .html file would allow for seamless integration

I've been searching extensively, but I haven't been able to locate exactly what I need. My goal is to merge my jQuery and CSS into a single .html file, but I'm struggling to get the jQuery functionality to work. Although I have experience wi ...

What happens if I attempt to pass a blank field in multer?

I am trying to verify if the image field passed to Multer will include the file. There are no errors being thrown by Multer and the server is currently processing the request. ...

New update in Fullcalendar v2: Enhancements to dayRender function for agenda view and agenda

For the newest version of FullCalendar, I am in need of the dayRender callback to modify the color of disabled days. Unfortunately, this specific callback only functions for month, basicWeek, and basicDay views. However, I require this functionality for a ...

Vue data will remain inaccessible until the JSON.stringify() function is executed

Dealing with this problem is tricky for me as it involves complex behavior that I haven't encountered before in JavaScript or Vue.js. I aim to simplify the code to focus on the most crucial aspects. I utilize vue-class-component (6.3.2) to define my ...

How asynchronous problems can affect the order of execution in jQuery when using $.load() with a bootstrap modal

Encountering a peculiar issue with the order of operations in jQuery. The code functions flawlessly in Internet Explorer 9 and 10, but fails to work in IE11, Firefox, and Chrome. It triggers the opening of a new window, but the load() function does not exe ...

Is it appropriate to include a function within a loop?

I'm curious to know if it's considered good practice to call a function inside a loop. Both of the following code snippets produce the same result, but I want to add clarity by using a function. Is this considered good practice? Thank you. Code ...

Preventing event propagation when clicking on a checkbox

When dealing with a checkbox that triggers an Ajax action on click, it can get tricky if the checkbox is inside a container with its own click behavior. The goal is to prevent the container click behavior from running when the checkbox is clicked. Here&apo ...