If you are like me, you almost never directly use
Setting up the POST request
You have three things you should setup (in addition to the URL) in your request for submitting a form via the POST method.
- The method needs to be set to POST.
- The Accept header should be set to format you expect back. In this example, it is set to
application/json. This is optional, but it is recommended.
- The body of the request needs to have the form data in the proper format: XML, JSON or
multipart/form-data. You can use the FormData class to format it as
multipart/form-datawhich is the format the browser would normally submit a form as.
Sending the request
Sending the request is straightforward: give fetch a URL and the options from the previous step, get a promise back. The promise will resolve with a Response object.
fetch(url, options): Promise<Response>
- url – the URL to make the call to
- options – the request options from the step before
Receiving the response
The response will include more than just the body, it carries the headers and more. If you use the Network tab in Chrome Developer Tools to inspect a response, you will be familiar then with the contents of the Response object.
Because you want JSON payload, you can use the
The fetch API is still in the early stages of being adopted by browsers. As such, the recent version of browsers support it, with the except of Safari. For backwards compatibility, Polyfill.io provides a polyfill. (Polyfill.io is a useful service because it uses browser detection to only send the polyfill to those browsers that need it.)
<script src="https://cdn.polyfill.io/v1/polyfill.min.js?features=fetch,Promise"> </script>