Now that we have learned how to process different types of API responses, let us look into how to customise our requests using options like HTTP methods, headers, and body.
The fetch()
method accepts two arguments url
and options
.
url
- the URL to be accessed.
options
- the most common fetch options are method
, headers
, and body
. This is an optional argument.
Let's look at the most commonly used options
in details:
-
method: Specifies the HTTP method for the request:
-
GET: Retrieve or read data from the server. It is the default value.
-
POST: Create or submit data to the server.
-
PUT: Update or replace existing data on the server.
-
DELETE: Remove or delete data from the server.
-
PATCH: To send specific changes or modifications, without replacing the entire data.
-
headers: Allows us to set custom headers for the request. This includes content type, authorization token, or any other headers required by the server.
-
body: It allows us to send data to the server in the request body.
Here's an example on sending data to a server using POST method:
Define the Data
We create an object postData
with the data that we want to send to the server.
Customise the Request
The HTTP method is set to POST and the headers specify that the data being sent is in JSON format using 'Content-Type': 'application/json'
. The body
contains the postData object, converted into JSON format using JSON.stringify()
.
Send the Request
The fetch()
function sends the data to the API endpoint: https://jsonplaceholder.typicode.com/post
. The await
keyword ensures that the response
variable holds the resolved value of the fetch operation.
Handle the Response
If the response is successful, response.json()
parses the returned JSON data. The parsed data is logged to the console.
Handle Errors
If there’s a problem during the fetch operation like network issues or server errors, the catch
block logs the error message.