I am trying to process a form submit, but the data that is sent to the server is coming back as undefined. I have tried to no avail debugging this file, but the console is returning Status code 200 even though the backend comes back as undefined. I am hoping you can help debug this and point me in the right direction to resolving this issue. Thank you in advance. Here is the code below:
What I have done
- Setup files on the front end with form to submit data
- Set up the server file that is going to process the data.
console.log(data) returns ‘undefined`
// "/pages/frontendfile.js"
import React, { useState } from "react";
export default function EmailConvTool({ openModal, setOpenModal }) {
const [open, setOpen] = useState(false);
const [selectedImage, setSelectedImage] = useState(null);
const [error, setError] = useState("");
const [beforeClick, setBeforeClick] = useState(
"Complete the form field below",
);
const initialEmailForm = {
email: "",
firstName: "",
lastName: "",
brand_url: "/someurl",
logo: "/images/file.png",
email_body: "",
};
const [emailForm, setEmailForm] = useState(initialEmailForm);
const [isClicked, setIsClicked] = useState(false);
const [beforeButton, setBeforeButton] = useState("Click to Send");
const [isEmailEmpty, setIsEmailEmpty] = useState(false);
const url = "/api/serverfile.js";
const handleClose = () => {
setOpenModal(false);
};
const handleChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
setEmailForm((prevState) => ({
...prevState,
[name]: value,
}));
};
const handleSubmit = async (e) => {
e.preventDefault();
setIsClicked(true);
if (emailForm.email === "") {
setIsEmailEmpty(true);
setBeforeClick("Enter your email in the form below");
return;
}
try {
const { email, firstName, lastName, brand_url, logo, email_body } =
emailForm;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
firstName,
lastName,
brand_url,
logo,
email_body,
}),
});
console.log("Server Response:", response); // returns Status code (200)
const data = await response.json(); // Parse the response as JSON
console.log("Parsed data", data); // returns Status code (200)
} catch (error) {
console.error(error);
setError(
"An error occurred while sending the email. Please try again or contact us for support.",
);
}
};
return (
<div>
<form onSubmit={handleSubmit}>
<div>
<div>
<div>
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
id="email"
disabled={isClicked}
placeholder="Enter your email"
value={emailForm.email}
onChange={handleChange}
/>
{isEmailEmpty && !emailForm.email && isClicked && (
<p className="text-red-500 text-xs mt-1">
Please enter your email address
</p>
)}
</div>
<div className="space-y-2">
<label htmlFor="firstName">First Name</label>
<input
type="text"
name="firstName"
id="firstName"
disabled={isClicked}
placeholder="Enter your first name"
value={emailForm.firstName}
onChange={handleChange}
/>
{isEmailEmpty && !emailForm.firstName && isClicked && (
<p>Please enter your first name</p>
)}
</div>
<div>
<label htmlFor="lastName">Last Name</label>
<input
type="text"
name="lastName"
id="lastName"
disabled={isClicked}
placeholder="Enter your last name"
value={emailForm.lastName}
onChange={handleChange}
/>
{isEmailEmpty && !emailForm.lastName && isClicked && (
<p>Please enter your last name</p>
)}
</div>
<div>
<button id="send" type="submit">
{error ? <p>{error}</p> : <p>{beforeButton}</p>}
</button>
</div>
</div>
</div>
</form>
</div>
);
}
// "/api/serverfile.js"
export default async function handler(req, res) {
const { data } = req.body;
if (req.method === "POST") {
try {
console.log(data); // returns undefined
res.status(200).json({ message: "success" });
} catch (error) {
console.log(error);
res.status(500).json({ message: error });
}
} else {
console.log(error);
}
}
>Solution :
You’ve got a mistake in your code. The server is confused by what the client sends
In your front-end you send the data like this:
body: JSON.stringify({
email,
firstName,
lastName,
brand_url,
logo,
email_body,
})
But on the server, you try to get that info with req.body.data. That’s why it says "undefined"
Here is how to change your server side code:
change this:
const { data } = req.body;
console.log(data); // returns undefined
to this:
const { email, firstName, lastName, brand_url, logo, email_body } = req.body;
console.log(email, firstName, lastName, brand_url, logo, email_body);