Content-type multipart/form-data vs application/json when submitting a form

Hello guys, sorry to disturb you all; consider the following code:
document.querySelector('#login').addEventListener('submit', (event) => {
event.preventDefault(); // Prevent default form submission

const formData = new FormData(event.target);

// Convert FormData to JSON
const formObject = {};
formData.forEach((value, key) => {
formObject[key] = value;
});

fetch('http://localhost:8080/M00967932/form.html', {
method: 'POST', // Specify the HTTP method
headers: { 'Content-Type': 'application/json' }, // Set JSON content type
body: JSON.stringify(formObject), // Send JSON string
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.text(); // Use response.json() if the server sends JSON
})
.then((data) => {
console.log('Success:', data); // Handle success
})
.catch((error) => {
console.error('Error:', error); // Handle errors
});
});
document.querySelector('#login').addEventListener('submit', (event) => {
event.preventDefault(); // Prevent default form submission

const formData = new FormData(event.target);

// Convert FormData to JSON
const formObject = {};
formData.forEach((value, key) => {
formObject[key] = value;
});

fetch('http://localhost:8080/M00967932/form.html', {
method: 'POST', // Specify the HTTP method
headers: { 'Content-Type': 'application/json' }, // Set JSON content type
body: JSON.stringify(formObject), // Send JSON string
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.text(); // Use response.json() if the server sends JSON
})
.then((data) => {
console.log('Success:', data); // Handle success
})
.catch((error) => {
console.error('Error:', error); // Handle errors
});
});
document.querySelector('#login').addEventListener('submit', (event) => {
event.preventDefault(); // Prevent default form submission

const formData = new FormData(event.target);

fetch('http://localhost:8080/M00967932/form.html', {
method: 'POST', // Specify the HTTP method
body: formData, // Send the FormData object
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json(); // Parse JSON response if applicable
})
.then((data) => {
console.log('Success:', data); // Handle success
})
.catch((error) => {
console.error('Error:', error); // Handle errors
});
});
document.querySelector('#login').addEventListener('submit', (event) => {
event.preventDefault(); // Prevent default form submission

const formData = new FormData(event.target);

fetch('http://localhost:8080/M00967932/form.html', {
method: 'POST', // Specify the HTTP method
body: formData, // Send the FormData object
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json(); // Parse JSON response if applicable
})
.then((data) => {
console.log('Success:', data); // Handle success
})
.catch((error) => {
console.error('Error:', error); // Handle errors
});
});
29 Replies
Faker
FakerOP2mo ago
I didn't understand, what is the difference between these 2 type of content-type ? My server can handle application/json but not multipart/form-data.... like here:
router.post('/form(.html)?', (req,res) => {
const { username, password } = req.body;
res.send(`Welcome, ${username}`);
})
router.post('/form(.html)?', (req,res) => {
const { username, password } = req.body;
res.send(`Welcome, ${username}`);
})
So when I try to send the form without using JSON.stringify in the body, I obtain an error with invalid json format But what I want to know, what is happening, I'm lost here, I know there are 2 content-type. When we use something like that in our server script app.use(express.json()); What are we saying here? How our server is able to handle json files ?
glutonium
glutonium2mo ago
how the server is handling the json file, there's no need to worry about it. i mean it's the same question as how does the server listen to a certain port. indeed it is something you can learn if u want, but this is nothing to worry about for you project ot when u r making a server in order to use json, the json that comes with the req needs some preprocessing. that preprocessing is done by express.json() middleware. now WHAT preprocessing it does, how it goes it is irrelevant u can access the data from req.body i think
Faker
FakerOP2mo ago
yep I see, thanks
glutonium
glutonium2mo ago
also the multipart form thingy form is a bit pain in the azz to work with i think u need the multar library for it search nodejs multar it let's u handle form data + files
Faker
FakerOP2mo ago
multer yes just installed it is it better to work with multipart or json ?
glutonium
glutonium2mo ago
if u r going to send files to the server then multar otherwise if just shrimple text data then i think either would work. but if u still have issues without multar then try with multar
Faker
FakerOP2mo ago
ok, ty !
glutonium
glutonium2mo ago
welcm btw I have a project i did long ago a backend project u can check it out and see if u can kind of understand what's going on not really sure how much it'll help u, but i was using most of the things u will be usign. like 90% u can also probably get an idea on how to structure your backend
glutonium
glutonium2mo ago
GitHub
GitHub - glutonium69/backend-practice
Contribute to glutonium69/backend-practice development by creating an account on GitHub.
Faker
FakerOP2mo ago
oki, will have a look, do you have a github ? ah ty !
glutonium
glutonium2mo ago
welcome
ἔρως
ἔρως2mo ago
it's actually a lot more complicated that that this indicates the type of data you are sending to the server multipart/form-data sends the POST content split by boundaries the server does it's magic to parse the body application/json means you're sending json data, which the server may or may not understand this is not`the same as a json file
glutonium
glutonium2mo ago
i JUST realised that i said json file and not json data after reading your msg o_O i was actually meaning json data but my monki brain said file but ya i can tell json file would be quite different and rather complicated than simple json data. sorry 😅😅
ἔρως
ἔρως2mo ago
it is important to distinguish both, because a json file is sent over multipart/form-data and json data can be sent as a file or over application/json
glutonium
glutonium2mo ago
i agree
ἔρως
ἔρως2mo ago
and don't forget the weird application/x-www-form-urlencoded basically, what you would send in a GET request url is sent in the body of the request
glutonium
glutonium2mo ago
hmmm i see
Faker
FakerOP2mo ago
oh json file and json data are 2 different things?
ἔρως
ἔρως2mo ago
yes like how xml data and an xml file are 2 different things soap servers use xml data, but sending an xml file is foreign to those imagine that you are expecting a voice call and i send you the graphic of the soundwaves over mail it's still my voice, but one is understandable to you and the other one is absolute nonsense
Faker
FakerOP2mo ago
yeah I see, so in the case of json file and json data, we can easily parse json data but not json file, right ?
ἔρως
ἔρως2mo ago
thats not what i said i said that the server expects json data, but you send it form data with a file in it, the server will reject the request it cant do anything with that
Faker
FakerOP2mo ago
yeah I see, it can't do anything about that because it didn't expect that data; this can change though if we use necessary libraries or methods ?
ἔρως
ἔρως2mo ago
nope if the server expects egg whites and all you give it is a pan with a boiled egg, what do you expect the server to do?
Faker
FakerOP2mo ago
hmm nothing, returns an error because it isn't something what it understands
ἔρως
ἔρως2mo ago
exactly so, if the server expects application/json and you send multipart/form-data, how do you want the server to respond to that?
Faker
FakerOP2mo ago
yep it can't but the thing is, I set up a small server for form submission... intially, I was getting an error because the server expect application/json while it was receiving multipart/form-data. Then, I needed to use a library called "multer" I forgot what it did but then it works
ἔρως
ἔρως2mo ago
ive never heard of multer and what the server accepts depends 300% of how it was configured
Faker
FakerOP2mo ago
yep I see, thanks !!
ἔρως
ἔρως2mo ago
you're welcome
Want results from more Discord servers?
Add your server