Sending a request to the back end server to be processed and then returning the result
The fetch method accepts two parameters. The first parameter is the URL address of the destination to which the fetch is being sent. This is known as the endpoint because the end of this destination address contains the data & methods necessary for proper processing.
The second parameter is optional and it’s a collection of options. The options are basically instructions on how the fetch request should be processed. These options can include the following CRUD operations; GET (capture and return data), DELETE (delete the identified data), POST (use input to create data), or PUT/PATCH (change existing data). If a fetch request does not identify one of those methods as an option, it will default to the GET method.
Now to demonstrate making fetch requests. Let’s say there’s an app called Great Dog Photos used by dog lovers all over the world.
The following fetch request could capture and return all the dog pictures stored for the user to view:
Since I did not pass in an option containing the GET method and only passed in the URL address as a parameter, the request implicitly defaulted to a GET request. The following option contains the GET method:
I can add that option to my fetch request to explicitly make a GET request to return all the dog pictures stored for the user to view:
To see a picture of a specific dog, I would simply add that dog’s unique ID number for example dog number 77:
The following fetch request is an example of how to delete dog number 77.
The POST and PUT/PATCH methods require input data to be sent in the fetch request. The input is extra instructions (body and headers) in addition to method inside of the option parameter.
PUT or PATCH
This fetch request will change data that already exists. For instance suppose I incorrectly saved the name of dog ID 100. To change its name from Kitty to the correct name, King, I would include the dog’s ID number and correct name in my fetch request:
NOTE Because I used PATCH, the body only needs to include the name being changed. If I used PUT, I would have to include the whole object, name and pic, in the body.