Fetch
The global fetch()
method is a browser-native promise-based JavaScript method that starts the process of fetching a resource from a network. The request that fetch()
sends to get data can be of any API that returns data of the format JSON or XML.
fetch("https://jsonplaceholder.typicode.com/users")
Unlike AJAX, fetch()
implicitly handles all stages of creating a request and receiving response; it returns a promise, which if fulfilled returns a reponse with a body text whose content can be accessed using .json()
method of the Response
interface.
How It Works
Fetch returns a Promise which is fulfilled once the response is available.
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => {
console.log(res.ok) // true
console.log(res.status) // 200
return res.json()
})
.then(data => console.log(data))
.catch(err => console.log(err))
res
is the response that resolved from the fulfilled Promise.
.json()
method reads the body text of the response and also returns a promise that evaluates to the JSON data.
When Does Fetch Fail?
Fetch API will not throw an error if you get back a 404, 500, or any other error HTTP response!
Fetch always succeeds, even if the API couldn’t send data because of a mistake in the requested URL.
The catch
method only executes in case of a connectivity problem or a network error.
Therefore, we can check the ok property of the response res.ok
to determine if a request actually failed.
fetch("https://jsonplaceholder.typicode.com/users/-1")
.then(res => {
if (res.ok) return res.json()
return Promise.reject(res)
})
.then(data => console.log(data))
.catch(res => console.error(res.status)) // 404
Modify Server Data with Fetch
The fetch function takes a second options object parameter which contains a large list of potential options.
fetch("https://jsonplaceholder.typicode.com/users/2", {
method: "DELETE"
})
This below code set is everything you need to do in order to pass JSON to an API.
fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST", //GET, POST, PUT, DELETE
body: JSON.stringify({ name: "Kyle" }),
headers: { "Content-Type": "application/json" }
})
.then(res => res.json())
.catch(err => console.error(err))
Axios
You can use a library like axios which is an abstraction over top of fetch that simplifies the API drastically.
Source: Fetch tutorial