i have an issue with my contact form. It send email but the user input is undefined. When i log the data on the console it is returned correctly but on vs code terminale all the information is undefined.
console log in browser dev tool return the below
{firstName: 'test ', email: 'test@test.com', phone: '382552', message: 'test '}
email: "test@test.com"
firstName: "test "
message: "test "
phone: "382552"
[[Prototype]]: Object
the console log in vs code terminal
{
to: 'info@test.com',
from: 'info@test.com',
subject: 'New message from undefined undefined',
text: '\n' +
' FirstName: undefined\r\n' +
'\n' +
' Email: undefined\r\n' +
'\n' +
' phone:undefined\n' +
' Message: undefined\r\n' +
'\n',
html: '\n' +
' FirstName: undefined<br />\n' +
' Email: undefined<br />\n' +
' phone:undefined\n' +
' Message: undefined<br />\n',
The message should be containing the details log on the browser console.
api/contact
import cookie from "cookie";
const mail = require("@sendgrid/mail");
mail.setApiKey(process.env.NEXT_PUBLIC_SENDGRID_API_KEY);
// eslint-disable-next-line import/no-anonymous-default-export
export default async (req, res) => {
res.setHeader(
"Set-Cookie",
cookie.serialize("token", req.body.token, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
expires: new Date(0),
maxAge: 60 * 60,
sameSite: "strict",
path: "/",
})
);
const body = JSON.parse(JSON.stringify(req.body));
const message = `
FirstName: ${body.firstName}\r\n
Email: ${body.email}\r\n
phone:${body.phone}
Message: ${body.message}\r\n
`;
const data = {
to: "info@test.com",
from: "info@test.com",
subject: `New message from ${body.firstName} ${body.phone}`,
text: message,
html: message.replace(/\r\n/g, "<br />"),
};
try {
await mail.send(data);
console.log(data);
res.status(200).json({ status: "OK" });
} catch (error) {
console.log("server error", error);
if (error.response) {
console.log(error.response.body);
}
res.status(400).json({ status: "ERROR", message: error.message });
}
};
JSON.stringify(JSON.parse(req.body)) seems like a waste of computer resources? This strategy is sometimes useful as the non-fastest way to deep clone an object (however structured clone:
which can easily be used like const clone = structuredClone(original); is easier to use and probably faster).body-parser the defacto node-js library for parsing the body. You should be able to console.log(req.body) and have that show everything.