Sendgrid可以在本地使用Nextjs,但在Vercel上托管时就不行了

5hcedyr0  于 2023-03-02  发布在  其他
关注(0)|答案(1)|浏览(169)

我让它在本地工作,但得到一个响应错误:未经授权在Vercel。
我已经在Sendgrid上创建了一个已验证的单个发件人验证。
我尝试在Sendgrid上创建一个新的API密钥,但它仍然不起作用。
我别无选择。
这是我在API路径中的代码:

import type { NextApiRequest, NextApiResponse } from "next";
const sgMail = require("@sendgrid/mail");

type EmailData = {
  to: string;
  from: string;
  subject: string;
  text: string;
  html: string;
};

type DataResponse = {
  data?: any;
  success: boolean;
  error?: string;
};

const emailAddress = process.env.SENDGRID_EMAIL as string;
const emailAddressTo = process.env.SENDGRID_EMAIL_TO as string;

sgMail.setApiKey(process.env.SENDGRID_API_KEY as string);

export default async function _(req: NextApiRequest, res: NextApiResponse<DataResponse>) {
  if (req.method !== "POST") {
    res.status(400).json({ success: false, error: "Invalid request" });
    return;
  }

  const data = JSON.parse(req.body);
  const { name, email, phone = "", message = "" } = data;

  console.log("sgMail", sgMail);
  console.log("--------------");
  console.log("process.env.SENDGRID_API_KEY", process.env.SENDGRID_API_KEY);
  console.log("--------------");
  console.log("SENDGRID_EMAIL", process.env.SENDGRID_EMAIL);
  console.log("--------------");
  console.log("SENDGRID_EMAIL_TO", process.env.SENDGRID_EMAIL_TO);
  console.log("--------------");

  const text = `
  Name: ${name} \r\n
  Email: ${email} \r\n
  Phone: ${phone} \r\n
  message: ${message} \r\n
`;

  let emailData: EmailData = {
    to: emailAddressTo,
    from: emailAddress,
    subject: "Form submission",
    text: text,
    html: `<div>${text.replace(/\r\n/g, "<br>")}</div>`,
  };

  try {
    await sgMail.send(emailData);
  } catch (error) {
    console.log(error);
    res.status(400).json({ success: false, error: "Error while sending email" });
    return;
  }

  res.status(200).json({ success: true, data: {} });
}

这是来自服务器的日志,其中包含以下错误消息:

sgMail MailService {
  client: Client {
    auth: 'Bearer HIDDEN BUT ITS THERE',
    impersonateSubuser: '',
    defaultHeaders: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'User-Agent': 'sendgrid/7.7.0;nodejs'
    },
    defaultRequest: {
      baseUrl: 'https://api.sendgrid.com/',
      url: '',
      method: 'GET',
      headers: {},
      maxContentLength: Infinity,
      maxBodyLength: Infinity
    }
  },
  substitutionWrappers: [ '{{', '}}' ],
  secretRules: [],
  MailService: [class MailService]
}
--------------
process.env.SENDGRID_API_KEY HIDDEN BUT ITS THERE
--------------
SENDGRID_EMAIL HIDDEN BUT ITS THERE
--------------
SENDGRID_EMAIL_TO: HIDDEN BUT ITS THERE
--------------
ResponseError: Unauthorized
    at node_modules/@sendgrid/client/src/classes/client.js:146:29
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 401,
  response: {
    headers: {
      server: 'nginx',
      date: 'Sun, 19 Feb 2023 20:57:56 GMT',
      'content-type': 'application/json',
      'content-length': '97',
      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',
      'strict-transport-security': 'max-age=600; includeSubDomains'
    },
    body: { errors: [Array] }
  }
}
n9vozmp4

n9vozmp41#

由于平台的动态特性,Vercel部署使用动态IP地址,并且在Sendgrid中,其IP访问管理处于打开状态,这意味着来自Vercel的所有请求都被阻止。

    • 解决方案:**

您可以禁用IP访问管理以重新打开对任何IP地址的帐户访问权限,并且不再维护允许的地址列表。
从设置→ IP访问管理页面,单击禁用允许列表。将打开一个对话框,要求您确认该决定。单击禁用。

相关问题