使用 Sendgrid/mail 和 nodejs 防止未处理的承诺拒绝

问题描述

我根本没有收到电子邮件,并且在 processticksAndRejections 的终端中收到错误消息。我不确定是否必须向我的函数添加异步来处理错误。我还尝试清除我的 npm 缓存,但我的错误没有任何变化。我的电子邮件被拒绝了,我有 cloudinary 附件,我可以在上传时在 cloudinary 仪表板中看到我的图像,但我没有收到发送到我的电子邮件的图像和表单的电子邮件

控制器/Feedback.js

const sgMail = require("@sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

exports.emailFeedback = (req,res) => {
  // console.log(req.body);
  const { name,email,message,phone,uploadedFiles } = req.body;
  const emailData = {
    to: process.env.EMAIL_TO,from: email,subject: "Feedback form",html: `
            <h1>Customer Feedback Form</h1>
            <hr />
            <h2>Sender name: ${name}</h2>
            <h2>Sender email: ${email}</h2>
            <h2>Sender message: ${message}</h2>
            <br />
            ${uploadedFiles.map((f) => {
              return `<img src="${f.secure_url}" alt="${f.original_filename}" style="width:50%;overflow:hidden;padding:50px;" />`;
            })}
            <hr />
            <p>https://Feedbackonline.com</p>
        `,};

  sgMail
    .send(emailData)
    .then((sent) => {
      console.log(sent);
      return res.json({
        success: true,});
    })
    .catch((err) => {
      console.log(err);
      return res.json({
        success: false,});
    });
};

当我将调用从 get 更改为 post 时,我在 localhost 中收到了无法获取 /api 的错误

解决方法

return 之前添加一个 sqMail(以使节点引擎“等待”异步结果)

return sgMail
    .send(emailData)
    .then((sent) => {

并像这样改进您的错误处理程序:

      return res
        .status(500)
        .json({
          error: err.message,success: false,});

这应该能更清楚地说明确切的问题。

,

我通过添加我要发送回复的电子邮件地址创建电子邮件发件人验证解决了这个问题。

// 此测试有效

const sgMail = require("@sendgrid/mail");

const API_KEY =
  "";

sgMail.setApiKey(API_KEY);

const message = {
  to: "zilahmusicpub@outlook.com",from: "tailoredr@mail.com",subject: "Hello from sendgrid",text: "Hello from sendgrid",html: "<h1>Hello from sendgrid to outlook</h1>",};

sgMail
  .send(message)
  .then((response) => console.log("Email sent..."))
  .catch((error) => console.log(error.message));