简体   繁体   English

使用 SendGrid + NextJS 提交 email 时出现 500 服务器错误

[英]500 server error when submitting email with SendGrid + NextJS

I'm trying to follow this tutorial to put an email capture form in a NextJS site: https://betterprogramming.pub/how-to-create-a-working-contact-form-in-next.js-459d1fc992ea我正在尝试按照本教程将 email 捕获表单放入 NextJS 站点: https://betterprogramming.pub/how-to-create-a-working-contact-form-in-next.js-459d1fc992ea

Because it's not a full contact form, I dropped all of the fields except the email.因为它不是完整的联系表,所以我删除了除 email 之外的所有字段。

My api/contact.js looks like this:我的 api/contact.js 看起来像这样:

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

mail.setApiKey(process.env.SENDGRID_API_KEY);

export default async (req, res) => {
  const body = JSON.parse(req.body);

  const message = `
    Email: ${body.email}
  `;

  const data = {
    to: 'SENDER-EMAIL',
    from: 'RECEIVER-EMAIL',
    subject: `New message from ${body.email}`,
    text: message,
    html: message.replace(/\r\n/g, '<br />'),
  };

  await mail.send(data);

  res.status(200).json({ status: 'OK' });
};

And inside index.js, the form looks like this:在 index.js 中,表单如下所示:

          <form onSubmit={handleSubmit} className={styles.form}>
          <label htmlFor="email">Email:</label>
          <input
            id="email"
            type="email"
            onChange={e => setEmail(e.target.value)}
          />
          <button type="submit">Send</button>
        </form>

The form displays properly on the site, but I get a 500 error when I try submit an email in production.表单在站点上正确显示,但是当我尝试在生产环境中提交 email 时出现 500 错误。 I also tried on localhost and got an error.我也在 localhost 上试过,但出现错误。

I npm installed the sendgrid package. I also have my secret in a.env.local.我 npm 安装了 sendgrid package。我在 a.env.local 中也有我的秘密。

I'm not sure what's going on.我不确定发生了什么。

It sounds like you are getting an error when you call on await mail.send(data) .听起来您在调用await mail.send(data)时遇到错误。 There could be a couple of reasons for this, but first we should see how to find out what the error is.这可能有几个原因,但首先我们应该看看如何找出错误是什么。

We need to wrap the call to send the email in a try/catch block.我们需要将发送 email 的调用包装在try/catch块中。 That way we can handle the error and inspect it to see what is wrong.这样我们就可以处理错误并检查它以查看问题所在。 We can also control the response to your front-end instead of dealing with the default 500 handler.我们还可以控制对您的前端的响应,而不是处理默认的 500 处理程序。

At the bottom of your api/contact.js function update to:在你的api/contact.js底部 function 更新为:

try {
  await mail.send(data);
  res.status(200).json({ status: 'OK' });
} catch (error) {
  console.log(error);
  if (error.response) {
    console.log(error.response.body);
  }
  res.status(400).json({ status: "ERROR", message: error.message });
}

Now when there is an error we log the error to the server logs and return a message to the front-end.现在,当出现错误时,我们将错误记录到服务器日志中,并向前端返回一条消息。 Note, that message may not be suitable for users and you might want to detect errors and return a better message yourself.请注意,该消息可能不适合用户,您可能希望自己检测错误并返回更好的消息。

Now you are logging the error you should be able to see what it says.现在您正在记录错误,您应该能够看到它说的是什么。 And it should direct you to what I think is one of these issues:它应该引导您解决我认为是这些问题之一的问题:

  • Your API key is wrong您的 API 密钥错误

    Either, you have set it incorrectly, or you added it to your .env.local correctly and need to fully restart your server要么,你设置不正确,要么你正确地将它添加到你的.env.local并且需要完全重启你的服务器

  • Your API key doesn't have permission to send emails您的 API 密钥没有发送电子邮件的权限

    When you create an API key, you can choose to give it all permissions or just a subset.当您创建 API 密钥时,您可以选择授予它所有权限或仅授予其一部分权限。 Make sure your API key has the permission to send emails.确保您的 API 密钥具有发送电子邮件的权限。

  • Your trying to send from an email address that SendGrid doesn't know you own您尝试从 SendGrid 不知道您拥有的 email 地址发送

    To send emails from an email address using SendGrid, you either need to verify the email address is yours or authenticate that the domain is yours (domain authentication is recommended for production applications)要使用 SendGrid 从 email 地址发送电子邮件,您需要 验证 email 地址是您的地址验证域是您的(生产应用程序建议使用域验证)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM