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
});
});
12 Replies
Faker
FakerOP2d 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
glutonium23h 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
FakerOP23h ago
yep I see, thanks
glutonium
glutonium23h 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
FakerOP23h ago
multer yes just installed it is it better to work with multipart or json ?
glutonium
glutonium23h 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
FakerOP23h ago
ok, ty !
glutonium
glutonium23h 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
glutonium23h ago
GitHub
GitHub - glutonium69/backend-practice
Contribute to glutonium69/backend-practice development by creating an account on GitHub.
Faker
FakerOP23h ago
oki, will have a look, do you have a github ? ah ty !
glutonium
glutonium23h ago
welcome
ἔρως
ἔρως11h 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
Want results from more Discord servers?
Add your server