Asked  7 Months ago    Answers:  5   Viewed   46 times

I'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the "No 'Access-Control-Allow-Origin'" error. Here's an example of the function I wrote:

exports.test = functions.https.onRequest((request, response) => {
  response.status(500).send({test: 'Testing functions'});
})

The function sits in this url: https://us-central1-fba-shipper-140ae.cloudfunctions.net/test

Firebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: https://firebase.google.com/docs/functions/http-events

This is how I did it:

var cors = require('cors');    

exports.test = functions.https.onRequest((request, response) => {
   cors(request, response, () => {
     response.status(500).send({test: 'Testing functions'});
   })
})

What am I doing wrong? I would appreciate any help with this.

UPDATE:

Doug Stevenson's answer helped. Adding ({origin: true}) fixed the issue, I also had to change response.status(500) to response.status(200) which I completely missed at first.

 Answers

14

There are two sample functions provided by the Firebase team that demonstrate the use of CORS:

  • Time server with date formatting
  • HTTPS endpoint requiring Authentication

The second sample uses a different way of working with cors than you're currently using.

Consider importing like this, as shown in the samples:

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

And the general form of your function will be like this:

exports.fn = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        // your function body here - use the provided req and res from cors
    })
});
Tuesday, June 1, 2021
 
shin
answered 7 Months ago
11

Update 2019-04-18

There is now a very simple way to deploy scheduled code on Cloud Functions through Firebase.

You can either use a simple text syntax:

export scheduledFunctionPlainEnglish =
functions.pubsub.schedule('every 5 minutes').onRun((context) => {
    console.log('This will be run every 5 minutes!');
})

Or the more flexible cron table format:

export scheduledFunctionCrontab =
functions.pubsub.schedule('5 11 * * *').onRun((context) => {
    console.log('This will be run every day at 11:05 AM UTC!');
});

To learn more about this, see:

  • The Scheduling Cloud Functions for Firebase blog post introducing the feature.
  • The documentation on scheduled functions.

Note that your project needs to be on a Blaze plan for this to work, so I'm leaving the alternative options below for reference.

If you want to schedule a single invocation of a Cloud Function on a delay from within the execution of another trigger, you can use Cloud Tasks to set that up. Read this article for an extended example of how that can work.

Original answer below...


There is no built-in runat/cron type trigger yet.

For the moment, the best option is to use an external service to trigger a HTTP function periodically. See this sample in the functions-samples repo for more information. Or use the recently introduced Google Cloud Scheduler to trigger Cloud Functions through PubSub or HTTPS:

enter image description here

I also highly recommend reading this post on the Firebase blog: How to Schedule (Cron) Jobs with Cloud Functions for Firebase and this video: Timing Cloud Functions for Firebase using an HTTP Trigger and Cron.

That last link uses cron-job.org to trigger Cloud Functions, and works for projects that are on a free plan. Note that this allows anyone to call your function without authorization, so you may want to include some abuse protection mechanism in the code itself.

Tuesday, June 1, 2021
 
Slinky
answered 7 Months ago
51

I see three steps in here:

  1. Calling a Cloud Function from Android.

    This is the same as calling any other HTTP URL from Android. See Calling a Cloud Function from Android through Firebase

  2. Parsing parameters from the call in your Cloud Function

    A HTTP triggered Cloud Function is really just an Express handler. So parsing the post works the same as for other Express handlers. The Firebase documentation for HTTP functions has some examples and links to other documentation.

  3. Posting to the database from a Cloud Functions

    All the samples in the functions-samples repo include the Firebase Admin SDK. This SDK allows you to access many Firebase features, such as the database, from within your function. But there's also an example in this repo.

Friday, August 20, 2021
 
alko989
answered 4 Months ago
89

If you want to update all child nodes, you can do something like this:

var ref = firebase.database().ref("comments"); // or admin.database().ref("comments")
ref.once("value").then((snapshot) => {
  var updates = {};
  snapshot.forEach((commentSnapshot => {
    var comment = commentSnapshot.val();
    var newRating = comment.rating + 1000;
    updates[commentSnapshot.key+"/rating"] = newRating;
  });
  ref.update(updates);
})

This performs a single multi-location update for all comments. Note that the performance benefit over performing separate updates is quite small, since Firebase pipelines the multiple requests over a single connection.

Also note that you should not put this in a Cloud Functions trigger on /comments, since that will lead to an endless loop: every time the comments get written, your function triggers, which updates the comments, which triggers the function again.

If you need this in Cloud Functions, you'll want to use a HTTP-triggered function, which is triggered by HTTP calls instead of database writes.

exports.updateCommentRatings = functions.https.onRequest((req, res) => {
  var ref = admin.database().ref("comments")
  ref.once("value").then((snapshot) => {
    var updates = {};
    snapshot.forEach((commentSnapshot => {
      var comment = commentSnapshot.val();
      var newRating = comment.rating + 1000;
      updates[commentSnapshot.key+"/rating"] = newRating;
    });
    ref.update(updates).then(() => {
      res.status(200).send("Comment ratings updated");
    });
  })
})

You can then periodically call this URL/function with a service like cron-job.org. For more on this see Cloud Functions for Firebase trigger on time?.

Tuesday, August 31, 2021
 
Kevin
answered 3 Months ago
49

To associate a vanity domain with your Cloud Functions, you need to associate them with Firebase Hosting. See the documentation on connecting the two.

Say you have a Cloud Function https://us-central1-<your-project-id>.cloudfunctions.net/bigben.

After making this connection the function will also be available on https://<your-project-id>.firebaseapp.com/bigben.

If you also connect a custom domain with Firebase Hosting, the function will also be available on https://<your-custom-domain>.com/bigben.

Monday, September 13, 2021
 
Cody
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share