0

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.

Joji
  • 4,703
  • 7
  • 41
  • 86
  • 1
    Read https://stackoverflow.com/questions/9870523/differences-in-application-json-and-application-x-www-form-urlencoded – Mridul Mar 16 '20 at 06:30
  • @Mridul I read this before I posted the question because it didn't answer my question about `formData` – Joji Mar 16 '20 at 06:49
  • FormData is preferred when we have to upload files like images to server. – Mridul Mar 16 '20 at 06:59
  • FormData is preferred when we have to upload files like images to server. – Mridul Mar 16 '20 at 06:59

0 Answers0