reactjs 获取错误:带有Sendgrid API的Next js应用程序中的"个性化设置"需要数组

ubof19bj  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(100)

我的API文件夹中有一个名为sendAlerts.js的文件,我一直收到错误:http://localhost:3000/api/sendAlerts中的personalizations需要数组
这是我在API/sendAlerts中的代码:

const mail = require('@sendgrid/mail');

mail.setApiKey(process.env.SENGRID_APIKEY);

export default async (req, res) => {
  await mail.send({
    personalizations: `${req.body.personalizations}`,
    from: 'david.gregory.medero@gmail.com',
    subject: `${req.body.subject}`,
    text: `${req.body.message}`
  });
  res.status(200).json({ status: 'Ok' });
}

下面是向该API端点提交消息的函数:

async function handleOnSubmit() {
    await fetch('/api/sendAlerts', {
      body: JSON.stringify({
        personalizations: [personalizationState],
        subject: `${product.title} in size ${variantTitle} is now available!`,
        message: `${product.title} in size ${variantTitle} is now available!`,
      }),
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
    })
  }

我的personalizationState在控制台中是这样的:
0:{收件人:数组(1),密件抄送:阵列(2)}
0:密件抄送:数组(2)0:{电子邮件:“dmederoudemy@gmail.com”} 1:{电子邮件:'dmedero@getwecked.com'}
到:数组(1)0:{电子邮件:'大卫.格雷戈里.梅德罗@gmail.com'}
我不知道为什么会出现该错误。我的personalizationState在数组中。我是否遗漏了什么???

pkmbmrz7

pkmbmrz71#

在API/sendAlerts文件中,您将send函数中的personalization属性设置为字符串。您需要删除从req获取个性化设置的模板文字。请参见此处:

const mail = require('@sendgrid/mail');

mail.setApiKey(process.env.SENGRID_APIKEY);

export default async (req, res) => {
  await mail.send({
    personalizations: req.body.personalizations, // no need for template literal assuming the personalizationState is an array
    from: 'david.gregory.medero@gmail.com',
    subject: `${req.body.subject}`,
    text: `${req.body.message}`
  });
  res.status(200).json({ status: 'Ok' });
}

此外,从您的personalizationState日志判断,您也不需要将其 Package 在数组中,因为它已经是一个数组。因此,在将消息提交到该API端点的函数中,您应该将其更改为:

personalizations: personalizationState, // personalizationState looks already like an array, no need for []

相关问题