r.Die
r.Die

Reputation: 165

Why would you use FormData over JSON in sending POST requests?

I haven't found a concrete answer to this question. Are there any benefits of using FormData or requests with application/x-www-form-urlencoded over just normal JSON with application/json. For example in Axios requests?

Upvotes: 7

Views: 6330

Answers (2)

JimithyPicker
JimithyPicker

Reputation: 134

It depends on what the server is accepting, typically if you're are interacting with an API you will send over JSON, which informs the server about the type of data being sent over. If you send it via a form, the content-type (in the header of the request), will be application/x-www-form-urlencoded.

So the server needs to be equipped, typically in the form of some type of middleware in order to parse it. For example, in express js, you would have something like the following,

// used to parse json
app.use(express.json());

app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

Upvotes: -1

Quentin
Quentin

Reputation: 944147

A FormData object can trivially:

  • Encode all the data in a <form>
  • Encode files without having to manually convert them to strings
  • Encode data in a format that is natively supported by common server-side environments like PHP (i.e. it will populate $_FILES and $_POST).

None of that applies to JSON.

Upvotes: 7

Related Questions