admin管理员组

文章数量:1357232

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?

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?

Share Improve this question asked Aug 10, 2020 at 20:18 r.Dier.Die 1653 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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 mon server-side environments like PHP (i.e. it will populate $_FILES and $_POST).

None of that applies to JSON.

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

本文标签: javascriptWhy would you use FormData over JSON in sending POST requestsStack Overflow