Sendgrid 在本地与 Nextjs 一起工作,但当我在 Vercel 上托管它时却不行

问题描述 投票:0回答:1

我让它在本地工作,但收到响应错误:在 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] }
  }
}
next.js sendgrid vercel
1个回答
0
投票

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

解决方案:

您可以禁用 IP 访问管理以重新打开对任何 IP 地址的帐户访问,并且不再维护允许的地址列表。

在“设置”>“IP 访问管理”页面中,单击“禁用允许列表”。 将打开一个对话框,要求您确认该决定。单击禁用。

© www.soinside.com 2019 - 2024. All rights reserved.