0

I'm trying to send push notifications between two devices for a tiny prototype. Both of them are Vue.js apps with firebase SDK integrated, so to implement a push notification flow I deployed a firebase function, but when I call it from any of devices, a CORS error is received as a response.

Both devices (mobile and desktop) have the same client code and knows the token of each other (storage into a firebase real-time database). The function only uses firebase messaging to send the push notification.

Firebase function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });

admin.initializeApp();

exports.notification = functions.https.onRequest((req, res) => {
    return cors(req, res, () => {
        if (req.method === "POST") {
            return admin.messaging().send(notification)
                .then(result => {
                    console.log(result);
                    res.status(200).send("ok")
                })
                .catch(err => res.status(500).send(err));
        } else {
            return res.status(400).send("Method not allowed");
        }
    });
});

Client code:

send(notification, token) {
    return fetch("https://[zone]-[project].cloudfunctions.net/notifications", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, notification })
    });
}

And the error is:

Access to fetch at 'https://[zone]-[project].cloudfunctions.net/notifications' from origin 'https://[project].web.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
lucasmenendez
  • 116
  • 1
  • 11
  • 1
    Are you sure the function is even getting invoked? What does the console log say? – Doug Stevenson May 30 '19 at 12:44
  • Thanks, @DougStevenson, I found the error. And it's as simple as I'm trying to a function with a wrong URI. The function URI its `/notification` and I am sending the request to `/notifications`. – lucasmenendez May 30 '19 at 12:57

2 Answers2

3

Could you use The functions.https.onCall trigger?

See https://firebase.google.com/docs/functions/callable .

The Cloud Functions for Firebase client SDKs let you call functions directly from a Firebase app. To call a function from your app in this way, write and deploy an HTTPS Callable function in Cloud Functions, and then add client logic to call the function from your app.

zkohi
  • 2,486
  • 1
  • 10
  • 20
  • I tried to change the function to callable but I got the same result. After that, I discovered that I'm so stupid and I'm trying to call the function with the wrong URI. Thanks a lot! – lucasmenendez May 30 '19 at 12:59
0

The URI that I used to invoke the function was wrong. It's solved. Sorry about that question.

lucasmenendez
  • 116
  • 1
  • 11