The Fetch API is the much simpler alternative to the XMLHttpRequest API . It is also the pure JavaScript alternative to JQuery’s ajax, get and post functions.
The Fetch API uses Promises to handle the result or callback. It usage is simple.
Example
fetch('https://your_url')
.then(response=>console.log(response))
.catch(err=>console.error(err))
The above example illustrates how to perform a get request by passing in the url, then you can handle the response using a promise , errors are caught in the catch block.
Options
You can customise the Fetch request by passing in some additional parameters, the supported list of parameters are
method
– GET
, POST
, PUT
, DELETE
, HEAD
headers
– object containing headers to be sent with the request
cache
– cache mode (default
, reload
, no-cache
)
referrer
– referrer of the request
mode
– cors
, no-cors
, same-origin
redirect
– follow
, error
, manual
Post Example
By setting the method attribute, you can send post requests with custom parameters.
fetch( your_post_url, {
method: 'POST',
body: {"key":"value"},
headers: new Headers({
'Content-Type': 'application/json'
}),
}).then(response => response.json())}
The above example makes a post request to the url passing in a JSON object containing data in the body parameter, it also sets a custom Content-Type header. It then gets the response and converts the response to a JSON object.