An unusual issue arises when an empty letter is received in the mail, indicating that all dynamic variables are undefined. There are no errors detected on either the server or client side. However, upon checking the console output of rec.body, the expected data does not appear.
The resulting outcome appears as follows:
body: { stream: undefined, source: null, length: null }
The API request function is structured like this:
const handleSubmitForm = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
// Sending data to the server
const response = await fetch('http://localhost:3000/api/sendMail', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
senderEmail: formInputs.email,
name: formInputs.name,
message: formInputs.message,
floortype: selectedFloor,
postcode: formInputs.postcode,
location: formInputs.location,
}),
});
if (response.ok) {
// Handling successful sending
console.log('Email successfully sent!');
} else {
// Handling sending error
console.error('Error sending email');
}
}
This is how the API code is structured:
import { NextApiRequest } from 'next';
import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1765787a767972797c78717b7919666274767c70087d787a">[email protected]</a>',
pass: '********',
}
});
interface MailData {
senderEmail: string;
name: string;
message: string;
floortype: string;
postcode: string;
location: string;
}
export async function POST(req: NextApiRequest) {
try {
// Parsing the request body as JSON
const { senderEmail, name, message, floortype, postcode, location }: MailData = req.body;
console.log(req)
// Email content
const mailOptions = {
from: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a1bcbeb2bdb6bdb8bcb5afbcbca1a093b4beb2babffdb0bcbe">[email protected]</a>',
to: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93e5fce5f2e0f2fda1a3a3a7d3f4fef2faffbdf0fcfe">[email protected]</a>',
subject: 'New Request from Visitor',
text: `Name: ${name}\nEmail: ${senderEmail}\nPostal Code: ${postcode}\nCity: ${location}\nDesired Flooring Type: ${floortype}\nQuestion: ${message}`,
};
await transporter.sendMail(mailOptions);
return NextResponse.json({ success: true });
} catch (error) {
console.error(error);
return NextResponse.json({ success: false, error: 'Error sending email' });
}
}