I am learning front end development and I learned there are essentially 3 ways to submitted data from a form using via a POST request.
let url = 'https://somewebsite.com/mock/login'
let data = {username:'admin', password:'123456'}
fetch(url, {
method:'POST',
headers: {
'Content-Type' : 'application/x-www-form-urlencoded'
},
body: Object.entries(data).map(pair => pair[0] + '=' + pair[1]).join('&')
})
fetch(url, {
method:'POST',
headers: {
'Content-Type' : 'application/json'
},
body: JSON.stringify(data)
})
let formData = new FormData()
formData.append('username', data.username)
formData.append('password', data.password)
fetch(url, {
method:'POST',
headers: {
'Content-Type' : 'multipart/form-data',
},
body: formData
})
But I don't really know the implications and differences among these three. What is the best practice?
I only know that , we have to use new FormData()
when uploading anything else but text, like a single image or multiple images, a blob, along with 'Content-Type': 'multipart/form-data'
And I guess the other two options that I showed below differ in how the sent data is encoded.