Nextjs 13 error: Trying to read property of undefined (reading 'headers')
P粉652495194
2023-08-31 16:47:14
<p>I'm having a problem with the headers of my post API endpoint created in Nextjs. </p>
<p>My endpoint is for form submission and I forward the input to my email. My current code can send the email and I receive it fine in my email, but every time I make a request it returns an error in the header. </p>
<pre class="brush:php;toolbar:false;">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 in 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 ${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 })
})
}</pre>
<p>I'm not sure what I did wrong. I read in a thread about doing the NextResponse in the return statement, but even that didn't work. </p>
<p>The error message I get:</p>
<pre class="brush:php;toolbar:false;"> - Error TypeError: Cannot read property 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)</pre></p>
I would say the problem is related to this question.
Your last two
return NextResponse...
are called inside thetransporter.sendMail()
callback, so they will not be retrieved from thePOST()
function return.Use Nodemailer's ability to return promises instead of using callback functions...
Another way is to convert the Nodemailer's callback into a promise, although in my opinion this is not concise enough