从 app/api/sendmail/route.ts 获取会产生 405 方法不允许。 Nextjs 14.1.0

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

使用 Nextjs 14.1.0 typescript 并在尝试使用 fetch 到无服务器 (Nodemailer) 函数 (sendemail.ts) 在我的应用程序中提交表单时面临 POST 请求问题。验证了正确的 URL(不再有 404 错误)和用于处理 POST 请求的服务器端代码。网络检查显示405方法不允许。寻求帮助来识别和解决此错误。任何见解将不胜感激。谢谢!

联系.tsx

 const [submissionError, setSubmissionError] = useState<string | null>(null);

  const handleSubmit = async (
    values: typeof initialValues,
    { setSubmitting }: { setSubmitting: (isSubmitting: boolean) => void }
  ) => {
    try {
      const response = await fetch("/api/sendmail", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(values),
      });

      if (!response.ok) {
        throw new Error("Failed to submit form");
      }

      console.log("Form submitted successfully");
    } catch (error) {
      console.error("Error submitting form:", error);
      setSubmissionError("Failed to submit form. Please try again later.");
    } finally {
      setSubmitting(false);
    }
  };

路线.ts


import { NextApiRequest, NextApiResponse } from "next";
import nodemailer from "nodemailer";

export async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === "POST") {
    const { name, mobileNumber, email, option, requirements } = req.body;

    try {
      
      const transporter = nodemailer.createTransport({
        host: "smtp.gmail.com",
        port: 587,
        secure: false, 
        auth: {
          user: "[email protected]",
          pass: "*****",
        },
      });

      // Send email
      await transporter.sendMail({
        from: "[email protected]", 
        to: "[email protected]", 
        subject: "New Contact Form Submission", 
        text: `
          Name: ${name}
          Mobile Number: ${mobileNumber}
          Email: ${email}
          Option: ${option}
          Requirements: ${requirements}
        `, 
      });

      res.status(200).json({ success: true });
    } catch (error) {
      console.error("Error occurred while sending email:", error);
      res.status(500).json({ success: false, error: "Failed to send email" });
    }
  } else {
    res.status(405).json({ success: false, error: "Method Not Allowed" });
  }
}

typescript next.js next.js13 nodemailer next.js14
1个回答
0
投票

您实际上是在混合

app router
(新路由器)和
pages router
(旧路由器)的模式。

在页面路由器中,我们可以在

pages/api
文件夹中创建一个文件,例如
pages/api/send-mail.js
,我们可以编写与您在此处提供的相同代码(第二个代码块),然后我们可以向它发送请求
fetch("/api/send-mail") 

但是在 NextJS 13.4 版本中引入的

app router
中。我们可以像您已经完成的那样创建一个文件:
app/api/send-mail/route.js
(我们可以将
api
文件夹命名为任何名称,但
api
更方便)。然后我们导出与大写方法同名的函数:

export const POST = (req: Request) => {
    const { name, mobileNumber, email, option, requirements } = await req.json()

    try {
        ...

        return Response.json({ success: true })
    } catch (e) {
        return new Response(JSON.stringify({ success: false }), {
            status: 500
        })
    }
}

您可以在官方文档中阅读有关路由处理程序的更多信息(https://nextjs.org/docs/app/building-your-application/routing/route-handlers

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