Encountering an issue with a POST request while trying to submit a form in my application using Nextjs 14.1.0 and TypeScript. The form is being submitted via fetch to a serverless function (sendemail.ts) for Nodemailer. I've confirmed that the URL is correct (no more 404 errors) and checked the server-side code for handling POST requests. Upon network inspection, it shows a 405 method not allowed error. I am looking for help in identifying and fixing this issue. Any insights or assistance would be greatly appreciated. Thank you!
Contact.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);
}
};
Route.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: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3054455d5d4970575d51595c1e535f5d">[email protected]</a>",
pass: "*****",
},
});
// Send email
await transporter.sendMail({
from: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f094859d9d89b0979d91999cde939f9d">[email protected]</a>",
to: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04607169697d446369656d682a676b69">[email protected]</a>",
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" });
}
}