Home > Software engineering >  Why do some fetch requests require you to include a second argument with an object?
Why do some fetch requests require you to include a second argument with an object?

Time:04-25

Why do some fetch requests require you to not only include a URL but include an Object with a property like method or headers?

It seems like every time I've encountered this, the method properties value is always set to 'POST'. Are there instances where this is not true? What do the headers do behind the scenes?

fetch('https://.....', {
     method: 'POST',
     headers: {
          'example': 'example',
          'example2': 'example2'
     }
}) ....

CodePudding user response:

If you call fetch without the second argument, it will make a default GET call with standard headers.

If you want to make a POST/PUT/PATCH/DELETE call on the other hand, since these verbs send data to the server and cause a database change, you need to send some extra information.
Headers for these verbs usually, amongst the default entries, carry some authorization bearer token, and define the content type of the body.
The body of the request is the most important entry, since it will carry the data that you want send to the server.
Basically the headers are key-value entries that are attached to the HTTP request, and they carry additional information about the type of request:

A request header is an HTTP header that can be used in an HTTP request to provide information about the request context, so that the server can tailor the response. For example, the Accept-* headers indicate the allowed and preferred formats of the response. Other headers can be used to supply authentication credentials (e.g. Authorization), to control caching, or to get information about the user agent or referrer, etc. MDN

  • Related