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

结果如下所示:

正文:{流:未定义,来源:空,长度:空}

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

推荐答案

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

  1. 在nextjs中,您不需要为从您的站点获取内容添加标题.因为默认情况下,NextJS会自动转发一些报头.
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.try
const requestData: MailData = await req.json();
      console.log(requestData)

Typescript相关问答推荐

更新:Typescript实用程序函数合并对象键路径

泛型类型,引用其具有不同类型的属性之一

迁移到Reaction路由V6时,获取模块Reaction-Router-Dom';没有导出的成员RouteComponentProps错误

在TypeScrip中分配回调时,参数的分配方向与回调本身相反.为什么会这样呢?

material 表不渲染任何数据

是否使用非显式名称隔离在对象属性上声明的接口的内部类型?

通配符路径与每条路径一起显示

如何在Reaction路由v6.4加载器和操作中获得Auth0访问令牌?

Angular 17子路由

有什么方法可以类型安全地包装import()函数吗?

从对象类型描述生成类型

有没有办法在Zod中使用跨字段验证来判断其他字段,然后呈现条件

为什么受歧视的unions 在一种情况下运作良好,但在另一种非常类似的情况下却不起作用?

TypeScript:如何使用泛型和子类型创建泛型默认函数?

为什么我会得到一个;并不是所有的代码路径都返回一个值0;switch 中的所有情况何时返回或抛出?(来自vsCode/TypeScript)

Karma Angular Unit测试如何创建未解析的promise并在单个测试中解决它,以判断当时的代码是否只在解决后运行

如何在TypeScript中声明逆变函数成员?

基于可选参数的动态类型泛型类型

类型为 `(callback: (...args: T) => void, params: T)` 的函数的泛型

可选字段和联合之间有什么区别吗?