We're having a bit of a discussion on the subject of posting data to a REST endpoint. Since the objects are quite complex, the easiest solution is to simply serialize them as JSON and send this in the request body.
Now the question is this: Is this kosher? Or should the JSON be set as a form parameter like data=[JSON]? Or is sending of JSON in the request body just frowned upon for forcing the clients using the application, to send their data via JavaScript instead of letting the browser package it up as application/x-www-form-urlencoded
?
I know all three options work. But which are OK? Or at least recommended?
JSON seems to have a lot of benefits over formData for sending data to server. Some of them include sending nested data without having to manually stringfy, or making possible a simple code like below to work: data() { return { form: {}, } }, methods: { submit() { this.
The main benefit of json over formdata is fields nesting! With json, you can nest fields as you want(dunno if there is a limit), but with formdata, you have to manually stringify the fields first and then add them as a string to the key that would own that nested object.
Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.
To post JSON data to the server, we need to use the HTTP POST request method and set the correct MIME type for the body. The correct MIME type for JSON is application/json. In this POST JSON example, the Content-Type: application/json request header specifies the media type for the resource in the body.
I'd say that both methods will work well it's important that you stay consistent across your APIs. The option I would personally choose is simply sending the content as application/json
.
POST
doesn't force you to use application/x-www-form-urlencoded
- it's simply something that's used a lot because it's what webbrowsers use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With