错误类型错误:无法读取undefined的属性(阅读'headers')- Nextjs 13

piwo6bdm  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(148)

我在Nextjs中创建的post API端点的标题中有问题。
我的端点是表单提交,在这里我获取输入并将其转发到我的电子邮件。我目前的代码发送电子邮件,我收到它刚刚好在我的电子邮件,但它不断返回错误的标题每次我提出请求。

import { NextResponse, NextRequest } from "next/server"
import nodemailer from "nodemailer"

export async function POST(request: NextRequest, response: NextResponse) {
  const formData = await request.formData()

  const emailValue = formData.get("email")
  const messageValue = formData.get("message")
  const numberValue = formData.get("phone_number")

  if (!messageValue || !numberValue || !emailValue) {
    return NextResponse.json({ message: "please fill all required fields!" }, { status: 400 })
  }

  const transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
      user: process.env.EMAIL,
      pass: process.env.PASSWORD,
    },
    tls: {
      rejectUnauthorized: false,
    },
  })

  const mailOptions = {
    from: `${emailValue}`,
    to: `${process.env.EMAIL}`,
    subject: `Message from contact me page from ${numberValue} - ${emailValue} `,
    text: `${messageValue}`,
  }

  transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
      return NextResponse.json({ message: `${err}` }, { status: 500 })
    }
    return NextResponse.json({ message: "Email sent successfully!" }, { status: 200 })
  })
}

字符串
我不知道我做错了什么。我在一个线程中读到关于在return语句中执行NextResponse的消息,但即使这样也不起作用。
我得到的错误是

- error TypeError: Cannot read properties of undefined (reading 'headers')
    at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:261:61)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

htrmnn0y

htrmnn0y1#

我认为这个问题与this issue有关。
最后两个return NextResponse...调用在transporter.sendMail()回调中,因此它们不会从POST()函数返回。
利用Nodemailer返回promise的能力,而不是使用回调...
如果未设置回调参数,则该方法返回Promise对象。

try {
  await transporter.sendMail(mailOptions);
  return NextResponse.json(
    { message: "Email sent successfully!" },
    { status: 200 },
  );
} catch (err) {
  return NextResponse.json({ message: err.toString() }, { status: 500 });
}

字符串
另一种方法是promis-ify Nodemailer回调,尽管在我看来它并不那么干净

return new Promise((resolve) => {
  transporter.sendMail(mailOptions, (err) => {
    const status = err ? 500 : 200;
    const message = err?.toString() ?? "Email sent successfully!";
    resolve(NextResponse.json({ message }, { status }));
  });
});

相关问题