【问题标题】:Firebase https onCall function blocked by corsFirebase https onCall 功能被 cors 阻止
【发布时间】:2023-03-29 16:18:01
【问题描述】:

我有一个sendMail 云功能,我想用它从我网站上的联系表单发送电子邮件。该网站托管在具有自定义 Google 域的 Firebase 上。问题是每当我尝试从托管站点调用该函数时都会收到此错误。

这是我迄今为止尝试过的

  1. 我已经尝试从浏览器本地测试该功能,它工作得很好。没有 cors 错误。
  2. 通过从 firebase shell 调用函数进行测试也可以正常工作,没有任何 cors 错误。

  1. 我检查了我的 Google Cloud 控制台并确保所有用户都可以调用该函数。

4。我也尝试过使用 cors 库来包装函数,但也没有用:

这是我如何调用我的 sendMail 函数:

handleSubmit = (e) => {
    e.preventDefault();
    const sendMail = firebase.app().functions('us-central1').httpsCallable("sendMail");
    
    sendMail({ details: this.state })
      .then((res) => {
        this.setState({
          loading: true,
        });
        this.notify("success");
      })
      .catch((error) => {
        this.notify(error);
      });
  };

这是整个sendMail函数:

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

admin.initializeApp();

// Use gmail to set up transporter
let transporter = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: functions.config().mail.user,
    pass: functions.config().mail.pass
  },
});

exports.sendMail = functions
  .region("us-central1")
  .https.onCall((data, context) => {
    const info = data.details;
    const mailOptions = {
      from: `${info.name} <${info.email}>`,
      to: functions.config().mail.dest,
      subject: info.subject,
      html: `<p style="font-size: 16px;">${info.name}, ${info.email}</p>
                    <p
                    style="
                        font-size: 1rem;
                        background: #FFECB3;
                        padding: 10px;
                        border-radius: 10px;">${info.message}</p>
                `, // email content in HTML
    };

    // returning results
    return transporter.sendMail(mailOptions, (err, info) => {
      if (err) {
        console.log("failed", err);
      }
    });
  });

我知道有人问过类似的问题,但我真的几乎尝试了所有方法。我只有在从我的 firebase 托管站点调用它时才会遇到 cors 问题。有人,请帮忙!

【问题讨论】:

  • 嗨@JilloAbdullahi 你能检查这两个案例herehere 并尝试他们的解决方案吗?那里展示了一些可能的解决方案以及声明和使用cors 库的正确方法,我相信它可能会对您有所帮助。
  • 嘿@gso_gabriel。我实际上意识到 cors 是为 onCall 函数自动处理的。问题是我没有在调用函数时包含区域的位上运行构建。只需要运行构建和重新部署。所有的头痛,但现在一切都很好。谢谢。

标签: reactjs firebase google-cloud-functions cors


【解决方案1】:

onCall 函数在 cors 方面的行为与 onRequest 不同,例如,您需要确保从同一区域调用它。见this post

如果您的函数出错,则可能会出现 cors 问题,值得检查模拟器和您的发送邮件响应。

【讨论】:

  • 调用函数时没有指定区域确实是个问题,因为我已经将它包含在定义中。刚刚解决了这个问题,一切都很好。谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2018-11-02
  • 2020-07-25
  • 2020-05-30
  • 2021-12-22
  • 2018-10-12
相关资源
最近更新 更多