JavaScript Fetch API
The Fetch API interface allows web browsers to make HTTP requests to web servers.
😀 No need for XMLHttpRequest anymore.
Browser Support
The table below shows the first browser versions that fully support the Fetch API:
Chrome
Edge
Firefox
Safari
Opera
42
14
40
10.1
29
Apr 2015
Aug 2016
Aug 2015
Mar 2017
Apr 2015
A Fetch API Example
The example below fetches a file and displays its content.
Example:
fetch(file) .then(response => response.text()) .then(data => myDisplay(data));Since Fetch is based on async and await, the example above might be easier to understand like this:
Example:
async function getText(file) { let response = await fetch(file); let data = await response.text(); myDisplay(data);}
Or even better: Use understandable names instead of generic ones.
Example:
async function getText(file) { let response = await fetch(file); let text = await response.text(); myDisplay(text);}
The Fetch API provides a more powerful and flexible feature set for making HTTP requests, and it integrates well with modern JavaScript features like Promises and async/await.