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.
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'
})
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})
})
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.
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))
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'
})
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.
fetch('https://reqbin.com/echo/get/json', {
headers: {
'X-Custom-Header': 'header value'
}
})
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...