How to send form data as json?
Answered
Yacare Caiman posted this in #help-forum
![Avatar](https://cdn.discordapp.com/embed/avatars/2.png)
Yacare CaimanOP
Hi guys, i made a server that receives json data and gives a response. Using curl, i am able to send and receive the data. How can i have a <form> component do the same? What would be the best method?
Answered by Yacare Caiman
Hi! Thank you for your reply â¤ï¸ , managed to make it work using something like this
const handleSubmit = async (event) => {
event.preventDefault();
setLoading(true)
const formData = new FormData(event.target);
const jsonData = JSON.stringify(Object.fromEntries(formData));
try {
const response = await fetch('http://localhost:3000/api/auth/step/1', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: jsonData,
});
if (response.ok) {
const data = await response.json();
setLoading(false)
setIsPasswordSet(data.is_password_set);
setGreeting(data.greeting);
if (data.is_password_set) {
} else {
router.push('/login/onboarding');
}
} else {
setErrorText(`Error: ${response.status}`);
}
} catch (error) {
setErrorText("Network error. Please try again.");
console.error(error);
}
};
2 Replies
![Avatar](https://cdn.discordapp.com/embed/avatars/4.png)
Chinese Egret
It depends as always XO. Is the endpoint using Next or different server?
![Avatar](https://cdn.discordapp.com/embed/avatars/2.png)
Yacare CaimanOP
Hi! Thank you for your reply â¤ï¸ , managed to make it work using something like this
const handleSubmit = async (event) => {
event.preventDefault();
setLoading(true)
const formData = new FormData(event.target);
const jsonData = JSON.stringify(Object.fromEntries(formData));
try {
const response = await fetch('http://localhost:3000/api/auth/step/1', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: jsonData,
});
if (response.ok) {
const data = await response.json();
setLoading(false)
setIsPasswordSet(data.is_password_set);
setGreeting(data.greeting);
if (data.is_password_set) {
} else {
router.push('/login/onboarding');
}
} else {
setErrorText(`Error: ${response.status}`);
}
} catch (error) {
setErrorText("Network error. Please try again.");
console.error(error);
}
};
Answer