使用Nodejs

时间:2017-04-06 04:59:28

标签: javascript json node.js ecmascript-6 sendgrid

如何使用Nodejs模拟SendGrid的内容?

我正在尝试使用SendGrid从应用程序中的联系表单发送电子邮件。我有一个Google Cloud功能,我通过HTTP帖子调用。我能够将表单数据作为JSON对象传递给我的Google Cloud Function,并在我的电子邮件内容中显示原始JSON对象,但是当我尝试模拟我的SendGrid内容时,JSON对象的属性将继续以未定义的形式返回。如何在SendGrid电子邮件内容中显示不同的formData属性?

以下是代码:

const functions = require('firebase-functions');

const sg = require('sendgrid')(
  process.env.SENDGRID_API_KEY || '<my-api-key-placed-here>'
);

exports.contactMail = functions.https.onRequest((req, res) => {
  contactMail(req.body);
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.send("Mail Successfully Sent!");
})


function contactMail(formData) {
  const mailRequest = sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: {
      personalizations: [{
        to: [{ email: 'my.email@gmail.com' }],
        subject: 'Contact Us Form Submitted'
      }],
      from: { email: 'noreply@email-app.firebaseapp.com' },
      content: [{
        type: 'text/plain',
        value: `
          You have received a contact us form submission. Here is the data:
          Name: ${formData.userFirstName} ${formData.userLastName}
          Email: ${formData.userEmail}
          Subject: ${formData.formSubject}
          Message: ${formData.formMessage}
        `
      }]
    }
  });

  sg.API(mailRequest, function (error, response) {
    if (error) {
      console.log('Mail not sent; see error message below.');
    } else {
      console.log('Mail sent successfully!');
    }
    console.log(response);
  });
}

每个模板表达式显示未定义。

但是,如果我的内容部分设置为:

content: [{
  type: 'text/plain',
  value: formData
}]

然后,电子邮件内容显示为原始JSON对象。

如何清理我的SendGrid电子邮件内容并以格式化,清晰的方式显示我的JSON数据?

1 个答案:

答案 0 :(得分:0)

问题是我的req.body是一个文本字符串,而不是一个JSON对象。

使用const formData = JSON.parse(req.body);然后将此变量传递给contactMail将在ES6模板文字中正确显示JSON对象的属性。

相关问题