为什么发送空字段?

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

有一个问题,邮件中收到一封空信,即所有动态变量都未定义。服务器端和客户端都没有错误。但是如果我将rec.body输出到控制台,我就不会收到传递给请求的数据。

结果如下所示:

body:{流:未定义,源:null,长度:null}

API 请求如下所示:

    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('Ошибка при отправке письма');
        }
    }

这就是 api 本身的样子:

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

const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
        user: '[email protected]',
        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: '[email protected]',
        to: '[email protected]',
        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: 'Ошибка при отправке письма' });
    }
}
typescript post next.js nodemailer
1个回答
0
投票

欢迎来到 Stack Overflow。问题是这样的:

  1. 在 nextjs 中,您不需要为从站点获取数据添加标头。因为nextjs默认会自动转发一些header。
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. 您没有收到数据,因为您需要先将其转换为 JSON。尝试一下
const requestData: MailData = await req.json();
      console.log(requestData)
© www.soinside.com 2019 - 2024. All rights reserved.