typescriptpostnext.jsnodemailer

Why are empty fields being sent?


There is a problem, an empty letter arrives in the mail, that is, all dynamic variables are undefined. There are no errors on either the server or client side. But if I output rec.body to the console, I don’t receive the data that I pass to the request.

The resulting result looks like this:

body: { stream: undefined, source: null, length: null }

The API request looks like this:

    const handleSubmitForm = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        
        // Отправка данных на сервер
        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) {
            // Обработка успешной отправки
            console.log('Письмо успешно отправлено!');
        } else {
            // Обработка ошибки отправки
            console.error('Ошибка при отправке письма');
        }
    }

And this is what the api itself looks like:

import { NextApiRequest } from 'next';
import { NextResponse } from 'next/server';
import nodemailer from 'nodemailer';

const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
        user: 'romanenkofloors@gmail.com',
        pass: '********',
    }
});

interface MailData {
  senderEmail: string;
  name: string;
  message: string;
  floortype: string;
  postcode: string;
  location: string;
}

export async function POST(req: NextApiRequest) {
    try {
      // Explicitly parse the request body as JSON
      const { senderEmail, name, message, floortype, postcode, location }: MailData = req.body;
      console.log(req)

      // Content of the email
      const mailOptions = {
        from: 'romanenkofloors@gmail.com',
        to: 'vovasan2004@gmail.com',
        subject: 'Новый запрос от посетителя',
        text: `Имя: ${name}\nEmail: ${senderEmail}\nПочтовый индекс: ${postcode}\nГород: ${location}\nТип желаемого покрытия: ${floortype}\nВопрос: ${message}`,
      };

      await transporter.sendMail(mailOptions);
      return NextResponse.json({ success: true });
    } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, error: 'Ошибка при отправке письма' });
    }
}

Solution

  • Welcome to Stack Overflow. Here's the issue:

    1. In nextjs you don't need to add headers for your fetching from your site. Because nextjs automatically forwards some headers by default.
    const response = await fetch('http://localhost:3000/api/sendMail', {
                method: 'POST',
                body: JSON.stringify({
                    senderEmail: formInputs.email,
                    name: formInputs.name,
                    message: formInputs.message,
                    floortype: selectedFloor,
                    postcode: formInputs.postcode,
                    location: formInputs.location,
                }),
            });
    
    1. You don't receive data because you need to convert it to JSON first. Try
    const requestData: MailData = await req.json();
          console.log(requestData)