Back to all resources
Fetch API
PUT request
error handling

Fetch - Put

By Jared Malan
This JavaScript code snippet demonstrates how to make a PUT request to a specified API endpoint using the Fetch API. The code updates a resource on the server with new data provided by the user.
 
Variables Initialization:
  • resource: This variable holds the identifier for the resource that needs to be updated. In this case, it is set to 1.
  • paramData: An object containing the data to be updated. Here, it includes a name and an age.

Fetch API Usage:
  • The fetch function is called with a URL constructed by appending the resource variable to the base URL. This targets the specific resource to be updated.
  • The second argument to fetch is an object specifying the HTTP method (PUT), headers (indicating the content type as JSON), and the body of the request, which is the JSON stringified version of paramData.

Handling the Response:
  • The response from the server is expected to be in JSON format, which is handled by calling .json() on the response object.
  • The resulting data is then logged to the console.

Error Handling:
  • Any errors encountered during the fetch operation, such as network issues or problems with the request, are caught and logged to the console using console.error.

This code is typically used in web applications where client-side JavaScript needs to update data on a server.