I have a simple form on a NextJS page, with the data stored in state:
const [bookingInfo, setBookingInfo] = useState({
name: "",
email: "",
phone: "",
});
const handleChange = (e) => {
setBookingInfo({ ...bookingInfo, [e.target.name]: e.target.value });
};
<form onSubmit={handleSubmit} className="flex-col">
<input
type="text"
name="name"
value={bookingInfo.name}
placeholder="name"
onChange={handleChange}
/>
<input
type="text"
name="email"
value={bookingInfo.email}
placeholder="email"
onChange={handleChange}
/>
<input
type="text"
name="phone"
value={bookingInfo.phone}
placeholder="phone"
onChange={handleChange}
/>
<button>Submit</button>
</form>
On submit I'm saving the data in localStorage via a function in my Context (where it shows up perfectly), and sending the data (hopefully) to my API route:
const handleSubmit = async (e) => {
e.preventDefault();
saveCustomerDetails(bookingInfo);
const response = await fetch("/api/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(bookingInfo),
});
console.log(response);
};
All I have in my API route at /api/checkout.js
for now is:
export default async function handler(res, req) {
try {
console.log(req.body);
} catch (error) {}
}
However the console logs 'undefined', and I get a warning undefined API resolved without sending a response for /api/checkout, this may result in stalled requests.
Any ideas what's going on?
CodePudding user response:
Your API handler has arguments in wrong order – req
comes before res
. Also you are getting API resolved without sending a response for /api/checkout, this may result in stalled requests.
because you are not sending any response with res
.
So your code should be:
export default async function handler(req, res) {
try {
console.log(req.body);
res.status(200).json({
message: 'Success', // just an example
});
} catch (error) {}
}