【问题标题】:CORS in Cloud Functions with typescript and axios带有 typescript 和 axios 的 Cloud Functions 中的 CORS
【发布时间】:2020-06-19 17:58:02
【问题描述】:

在我的反应应用程序中,我正在向云函数名称和电话发送具有 2 个属性的发布请求,但在反应应用程序中返回来自 CORS 的限制,我正在使用带有 Typescript 的云函数 这是我的反应应用程序中的代码

        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);
          });
      }); ```

这是来自我的云功能:

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)

    }

    });

这是我得到的错误:

从源“http://localhost:3000”获取“https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

【问题讨论】:

  • 问题中引用的错误消息表明 https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback 端点未配置为以 CORS 工作所需的方式响应 OPTIONS 请求。该端点必须配置为以 200 OK 成功响应响应未经身份验证的 OPTIONS 请求。现在它显然正在响应一些其他 HTTP 状态代码:可能是 405 错误或其他一些 4xx 错误。
  • 是的,但我使用 res.set(Access-Control-Allow-Headers) 进行了配置,没有我的 try-catch 工作正常,但是当我将它放入我的函数时会出现该消息跨度>
  • 你检查过实际的 HTTP 状态码是什么吗?您可以使用浏览器开发工具中的网络窗格进行检查。
  • 它是:错误:请求失败,状态码为 500
  • 是的,你有一个 500 问题。您没有 CORS 问题。如果您修复了 500 错误的原因,您可能会发现您当前的 CORS 配置已经按预期工作。要解决 500 问题,您可以查看 https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback 端点的服务器日志,并查看在服务器响应该 500 之前那里记录了哪些消息。但是鉴于问题中显示的代码,它看起来可能是你自己的抛出 500 的代码——因为 try 块中的代码失败了。

标签: typescript google-cloud-firestore axios google-cloud-functions


【解决方案1】:

您将在文档中找到here,详细了解如何启用 CORS 支持。所以以下应该可以解决问题(未经测试):

//...

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);
        }

    });

});

【讨论】:

  • 我收到一个错误:错误:请求失败,状态码为 500,我按你说的那样写
  • 您在 Cloud Functions 控制台中看到任何错误吗?
  • @RodolfoCampos 您好,您有时间查看建议的解决方案吗? Cloud Functions 控制台中是否有任何错误?
  • 感谢您的回答,对不起,我没有,毕竟这对我的项目来说不是必需的,但我认为您的回答是正确的。
  • 我必须修改答案才能使其正常工作。尝试使用“cors”中的 import cors; ,它应该可以正常工作
猜你喜欢
  • 2020-09-24
  • 1970-01-01
  • 2021-11-24
  • 2021-04-15
  • 2016-06-12
  • 1970-01-01
  • 2017-08-02
  • 2020-07-25
  • 2019-10-21
相关资源
最近更新 更多