【问题标题】:CORS Error Firebase Cloud Functions in React Contact Form反应联系表中的 CORS 错误 Firebase 云函数
【发布时间】:2020-08-16 13:14:58
【问题描述】:

我有一个 react 联系表单,其中一个 firebase 云功能处理使用 nodemailer 发送电子邮件和一个 axios post 请求以将数据存储在我的 firestore db 中。我在我的函数中使用 CORS,但在提交表单时仍然在我的控制台中收到 CORS 错误。

从源“http://localhost:3000”访问“https://.cloudfunctions.net/submit”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头.我花了大约 2 个小时在谷歌上搜索,从我读到的内容看来,如果我有 const cors = require('cors')({origin: true});它应该工作。任何帮助都会很棒。

const functions = require('firebase-functions');
const nodemailer = require('nodemailer');
const cors = require('cors')({origin: true});
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;

const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword,
  },
});

exports.submit = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    if (req.method !== 'POST') {
      return;
    }
    const mailOptions = {
      from: req.body.email,
      replyTo: req.body.email,
      to: gmailEmail,
      subject: `${req.body.name} submitted a quote request!`,
      text: req.body.message,
      html: `<p>{req.body.message}</p>`,
    };
    mailTransport.sendMail(mailOptions).then(() => {
      console.log('New email sent to:', gmailEmail);
      res.status(200).send({ isEmailSend: true });
      return;
    });
  });
});


// This snippet is in my contact.js component
const sendEmail = () => {
    axios
      .post(
        'https://<myurl>.cloudfunctions.net/submit',
        formData
      )
      .then((res) => {
        db.collection('emails').add({
          name: formData.name,
          email: formData.email,
          phone: formData.phone,
          message: formData.message,
          time: new Date(),
        });
      })
      .catch((err) => {
        console.log(err);
      });
  };

【问题讨论】:

  • 没有帮助解决问题
  • CORS 通常在服务器端配置。你已经在 Firebase 中做过了吗?
  • 我在我的 functions/index.js 文件中添加了 cors 包,这是 firebase 云功能。还有其他地方应该做的吗?

标签: reactjs firebase google-cloud-firestore google-cloud-functions nodemailer


【解决方案1】:

我删除了云功能并重新创建它,我不再遇到 cors 问题。

【讨论】:

    猜你喜欢
    • 2020-08-25
    • 2020-07-07
    • 2018-07-27
    • 2018-05-15
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2021-05-06
    相关资源
    最近更新 更多