为什么我的SendGrid函数返回“服务不可用”?

时间:2020-06-11 13:13:45

标签: typescript firebase google-cloud-functions sendgrid

我是SendGrid的新手,并尝试使用Firebase Cloud函数从后端向我的React.js应用发送电子邮件。 当有人要发送消息时,我将文档写入Firestore。然后,我听那个集合,并在创建文档时从云功能发送电子邮件。

我正在尝试使其正常运行,但是不断在我的云函数中记录错误以及此错误消息:

Error: Service Unavailable
    at axios.then.catch.error (node_modules/@sendgrid/client/src/classes/client.js:133:29)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

编辑:我已经在catch语句中捕获了该错误,并获得了有关此错误的更多详细信息。这是完整的日志:

{ Error: Forbidden
    at axios.then.catch.error (node_modules/@sendgrid/client/src/classes/client.js:133:29)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)
  code: 403,
  message: 'Forbidden',
  response: 
   { headers: 
      { server: 'nginx',
        date: 'Thu, 11 Jun 2020 17:03:27 GMT',
        'content-type': 'application/json',
        'content-length': '281',
        connection: 'close',
        'access-control-allow-origin': 'https://sendgrid.api-docs.io',
        'access-control-allow-methods': 'POST',
        'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-of, x-sg-elas-acl',
        'access-control-max-age': '600',
        'x-no-cors-reason': 'https://sendgrid.com/docs/Classroom/Basics/API/cors.html' },
     body: { errors: [Array] } } }

编辑2: 因此,我已经按照错误https://sendgrid.com/docs/for-developers/sending-email/cors/中的链接进行了操作,如果我没做错,这表明它阻止了我,因为我试图对他们的API进行基于浏览器的调用?但是事实并非如此。我正在通过云功能拨打电话。

我无法弄清楚我做错了什么,还是我很不幸,在SendGrid遇到某些问题(Service Unavailable)时第一次尝试实现它。

这是我定义sgMail的方式:

import * as sgMail from "@sendgrid/mail";
const SENDGRID_API_KEY = functions.config().sendgridfull.key;
sgMail.setApiKey(SENDGRID_API_KEY);

这是我的云函数,我已经检查了所有变量,它们都存在。

exports.firestoreEmail = functions.firestore
  .document("email_messages/{messageID}")
  .onCreate((snap, context) => {
    const msgData = snap.data();
    if (!msgData) return;

    return db
      .collection("users")
      .doc(msgData.recipient_ID)
      .get()
      .then((doc) => {
        const recipientData = doc.data();
        if (!recipientData) return;

        const promises: any = [];

        const msg = {
          to: recipientData.email,
          from: msgData.sender_email,
          templateId: "d-myRandomTemplateId",
          dynamic_template_data: {
            sender_name: "Some One",
          },
        };

        const msg2 = {
          to: msgData.sender_email,
          from: recipientData.email,
          templateId: "d-myRandomTemplateId",
          dynamic_template_data: {
            sender_name: "Some One",
          },
        };



        promises.push(sgMail.send(msg));
        promises.push(sgMail.send(msg2));

        return Promise.all(promises);
      });
  });

1 个答案:

答案 0 :(得分:1)

请检查此github issue,其中它指定如何使用sgMail.send方法,这将导致Cloud Function返回服务不可用错误。

send和sendMultiple方法返回一个Promise,因此您可以处理成功并捕获错误:

sgMail
  .send(msg)
  .then(() => {
    // Celebrate
  })
  .catch(error => {
    // Log friendly error
    console.error(error);

    if (error.response) {
      // Extract error msg
      const {message, code, response} = error;

      // Extract response msg
      const {headers, body} = response;

      console.error(body);
    }
  });

或者,您可以将回调函数作为最后一个参数传递:

sgMail
  .send(msg, (error, result) => {
    if (error) {
      // Do something with the error
    }
    else {
      // Celebrate
    }
  });

请告诉我它是否有效。