2
votes

In my react app I'm sending a post request with 2 attributes to a cloud function name and phone but returns a restriction from CORS in the react app, I am using cloud functions with Typescript This is my code from my react app

        axios
          .post(
            "https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback",
            {
              name: `${this.state.contactName}`,
              phone: `${this.state.phone}`,
            }
          )
          .then(function(response) {
            // eslint-disable-next-line no-console
            console.log(response);
          })
          .catch(function(error) {
            // eslint-disable-next-line no-console
            console.log(error);
          });
      }); ```

And this is from my cloud function:

exports.firestoreTtlCallback = functions.https.onRequest(async(req , res) => {
    res.set('Access-Control-Allow-Origin', "*")
    res.set('Access-Control-Allow-Methods', 'GET, POST')
    res.set('Access-Control-Allow-Headers', 'Content-Type');

    const name = req.body.name;
    console.log(name)
    //recibir nombre de contacto y numero de telefono
    const payload = req.body as ExpirationTaskPayload
    try {

        // buscar usuario y obtener token
        const user = await db.collection('users').doc(payload.uid).get()
        const data:any = user.data()
        const counter = await admin.firestore().collection("users").doc(payload.uid).collection("kards").doc("0").collection("kardsRef").get();
        const doc = await admin.firestore().doc(`/users/${payload.uid}/kards/0/kardsRef/${counter.size}`)
        doc.set({ msg: "hola" })
        var message = {
            data: {
              score: '850',
              time: '2:45'
            },
            token: data.token
          };
        //enviar notificacion
        await admin.messaging().send(message)

        // Response is a message ID string.
        // borrar notificacion firestore
        await admin.firestore().doc(payload.docPath).delete()
        return res.status(200).send(`Task has been executed`);
    }
    catch (error) {
        console.error(error)
        return res.status(500).send(error)

    }

    });

this is the error I get:

Access to fetch at 'https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

1
The error message cited in the question indicates the https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback endpoint isn’t configured to respond to OPTIONS requests in the way that’s necessary for CORS to work. That endpoint must be configured to respond to unauthenticated OPTIONS requests with a 200 OK success response. Right now it’s apparently responding with some other HTTP status code: maybe a 405 error or some other 4xx error. - sideshowbarker
yeah but I'm configuration that with the res.set(Access-Control-Allow-Headers), without my try-catch works fine but when I put it in my function appears that message - Rodolfo Campos
Have you checked what the actual HTTP status code is? You can use the Network pane in browser devtools to check. - sideshowbarker
its a : Error: Request failed with status code 500 - Rodolfo Campos
So yeah, you have a 500 problem. You don’t have a CORS problem. If you fix the cause of the 500 error, you’re may find that your current CORS config is already working as expected. To troubleshoot the 500 problem, you can look through the server logs for the https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback endpoint, and see what messages are getting logged there before the server responds with that 500. But given the code shown in the question, it looks like it might be your own code that’s throwing the 500 — because the code in the try block fails. - sideshowbarker

1 Answers

1
votes

You'll find here in the doc the details on how to enable CORS support. So the following should do the trick (untested):

//...

import * as cors from 'cors';

const corsOptions = { origin: true };
const corsMiddleware = cors(corsOptions);

//...

exports.firestoreTtlCallback = functions.https.onRequest(async (req, res) => {

    corsMiddleware(req, res, () => {

        const name = req.body.name;
        console.log(name);
        //recibir nombre de contacto y numero de telefono
        const payload = req.body as ExpirationTaskPayload;
        try {
            // buscar usuario y obtener token
            const user = await db
                .collection('users')
                .doc(payload.uid)
                .get();
            const data: any = user.data();
            const counter = await admin
                .firestore()
                .collection('users')
                .doc(payload.uid)
                .collection('kards')
                .doc('0')
                .collection('kardsRef')
                .get();
            const doc = await admin
                .firestore()
                .doc(`/users/${payload.uid}/kards/0/kardsRef/${counter.size}`);
            doc.set({ msg: 'hola' });
            var message = {
                data: {
                    score: '850',
                    time: '2:45'
                },
                token: data.token
            };
            //enviar notificacion
            await admin.messaging().send(message);

            // Response is a message ID string.
            // borrar notificacion firestore
            await admin
                .firestore()
                .doc(payload.docPath)
                .delete();
            return res.status(200).send(`Task has been executed`);
        } catch (error) {
            console.error(error);
            return res.status(500).send(error);
        }

    });

});