fetch
function?fetch()
function is a global method by JavaScript which allows us to retrieve resources asynchronously across the network
fetch
different from ajax
call?fetch()
will not reject on HTTP error status (e.g. 404 & 500). It will resolve with ok
status set to false
insteadfetch()
will not receive cross-site cookies
fetch()
will not send cookies. Unless specially set in the init
optionfetch
function work?fetch
takes in one or more arguments. For the most basic case, fetch
just takes in one argument which is the path
to the resource you want to fetch.
1
fetch('http://example.com/movies.json')
fetch
function returns a promise
which is a Response
object. In order to extract the body of content from the Response
object, you need to use Body mixin
of the Fetch API
(More information can be found here https://developer.mozilla.org/en-US/docs/Web/API/Body)
1 2
const response = await fetch('http://example.com/movies.json'); const myJson = await response.json();
.then
methodWhat we are trying to achieve here are:
fetch
a local file rainbow.jpg
response
containing the file with all the meta-data
of the request. This is also a promisepromise
using another .then
to get the blob
image.getElementById
URL.createObjectURL
is used to convert the format of the blob
to something which is usable by the <img>
tag1 2 3 4 5
fetch('rainbow.jpg').then(response => { return response.blob(); }).then(blob => { document.getElementById('rainbow').src = URL.createObjectURL(blob); })
Another example
1 2 3 4 5 6 7
const myImage = document.querySelector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg') .then(res => res.blob()) .then(res => { const objectURL = URL.createObjectURL(res); myImage.src = objectURL; });
async/await
methodWhat we are trying to achieve here are:
await
for the fetch
request from an external linkawait
for the json
content of the response
to be extractedconsole.log
the string
format of the json
1 2 3
const response = await fetch('http://example.com/movies.json'); const myJson = await response.json(); console.log(JSON.stringify(myJson));
Another example with similar concept:
blogs[postId].file
returns the path to the file which I want to fetch
1 2 3 4 5
const getBlogContent = async (postId: string) => { const response = await fetch(blogs[postId].file); const text = await response.text(); await setText(text); };