Back to all resources
Fetch API
HTTP POST
Promise
JSON
Error Handling

Fetch - Post

By Jared Malan
Documentation:


This is a JavaScript code snippet that makes a POST request to a specified URL using the Fetch API. The URL in this case is 'https://api.example.com/data'. The request is made with a header specifying the content type as 'application/json'. The body of the request is a JSON stringified object containing two properties: name and age, with values 'John' and 30 respectively.

The Fetch API returns a Promise that resolves to the Response object representing the response to the request. This is processed by the first 'then' method, which uses the json() method to parse the response body as JSON. 

The second 'then' method receives the resulting data and logs it to the console. If any error occurs during the request or processing the response, it is caught by the 'catch' method and logged to the console as an error.