Summary of How to send Bearer Token with JavaScript Fetch API?

  • reqbin.com
  • Article
  • Summarized Content

    What is Fetch API?

    The Fetch API is a modern and powerful alternative to the XMLHttpRequest object for making asynchronous HTTP requests (AJAX requests) from JavaScript. It introduces a new global fetch() method that allows network requests to be made in a more flexible and cleaner way.

    • Fetch API uses Promises, which simplifies the API and avoids callbacks.
    • It can be easily used in conjunction with other technologies like Service Workers.
    • The main advantage over XMLHttpRequest is its simpler and cleaner API.

    Sending Authorization Headers with Fetch API

    By default, Fetch API requests do not include user credentials like cookies or HTTP authentication headers. To include these, you must explicitly set the 'credentials' option when calling fetch(). Here's an example of sending a Bearer Token Authorization Header:

    fetch('https://reqbin.com/echo/get/json', {
      headers: {Authorization: 'Bearer Token'},
      credentials: 'include'
    })
    • Setting 'credentials: "include"' allows sending credentials for same-origin and cross-origin calls.
    • 'credentials: "same-origin"' sends credentials only to the origin domain.
    • 'credentials: "omit"' prevents sending credentials altogether.

    Sending JSON Data with Fetch API

    To send JSON data to the server using Fetch API, you need to include the 'Content-Type' header and stringify the data in the request body. Here's an example of sending a POST request with JSON data:

    fetch('https://reqbin.com/echo/post/json', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({orderId: 1})
    })

    Sending HTML Form Data with Fetch API

    To submit HTML form data to the server with Fetch API, you need to create and populate a FormData object and pass it to the fetch() request along with the POST method. For example:

    let data = new FormData();
    data.append('orderId', '1');
    data.append('customer', 'John Smith');
    		
    fetch('https://reqbin.com/echo/post/form', {
      method: 'POST',
      body: data
    })

    Note that you don't need to specify the Content-Type header yourself, as Fetch API will automatically add the 'Content-Type: multipart/form-data' header.

    Retrieving JSON and XML Responses

    To retrieve JSON data from the server's response, you can use the response.json() method, which returns a Promise that resolves with the JSON data. For example:

    fetch('https://reqbin.com/echo/get/json')
       .then(resp => resp.json())
       .then(json => console.log(json))

    Similarly, to retrieve XML data, you can use the response.text() method, which returns a Promise that resolves with the XML data:

    fetch('https://reqbin.com/echo/get/xml')
       .then(resp => resp.text())
       .then(xml => console.log(xml))

    Making Other HTTP Method Requests

    Fetch API supports all HTTP methods, including GET, POST, PUT, PATCH, and DELETE. To specify the HTTP method, pass the 'method' option to the fetch() call. For example, to make a DELETE request:

    fetch('https://reqbin.com/echo/delete/json', {
      method: 'DELETE'
    })

    Handling HTTP Headers in Fetch API

    You can include HTTP headers in Fetch API requests by passing a headers object as an option to the fetch() call. However, there are some restrictions on the header names you can send due to security reasons and automatic header calculations. For example, you cannot set the 'Content-Length', 'Host', 'Referer', or 'Access-Control-Request-Headers' headers manually.

    • To send custom headers, include them in the headers object:
    • fetch('https://reqbin.com/echo/get/json', {
        headers: {
          'X-Custom-Header': 'header value'
        }
      })

    Fetch API Error Handling

    Fetch API uses Promises, so you can handle errors using the catch() method. Here's an example:

    fetch('https://reqbin.com/echo/get/json')
       .then(resp => resp.json())
       .then(json => console.log(json))
       .catch(error => console.error(error))

    Ask anything...

    Sign Up Free to ask questions about anything you want to learn.