<?xml version="1.0" encoding="UTF-8"?> <book> <id>29633913</id> <status>Want To Read</status> </book>
{ "book": { "id": 29633913, "status": "Want to Read" } }
API
At a high level, Fetch is used to make HTTP requests.
It uses Promises to handle the asynchronous nature of HTTP requests and responses.
Default request
GET requests are used to retrieve information from the server
Here's what a GET request might look like using the Fetch API:
fetch("https://jservice.xyz/api/games") .then(function(res) { console.log("response: ", res); return res.json(); }) .then(function(data) { console.log("data:", data); });
fetch's first argument is the URL that you want to make a request to (the path to the resource you want to fetch)options objectfetch:fetch returns a Promise that resolves with a Fetch Response object.
status and url..json() method takes that stream and returns a promise that resolves with the result of parsing the body text as JSON.json() method is the equivalent of using JSON.parse() except that it works on a ReadableStream instead of just a string.// with promises/catch const handleClick = () -> { fetch("/name") .then(res => { if (!res.ok) { throw res; } }) .then(data => { document.querySelector('h1').innerHTML = data.name; }) .catch(err => { err.json().then(errorJSON => { document.querySelector('div').innerHTML = errorJSON.message }); }); }; // with async/await const handleClick = () => { const res = await fetch('/name'); // localhost: 3000/name const json = await res.json(); debugger if (!res.ok) { document.querySelector('h1').innerHTML = json.error; } else { document.querySelector('div').innerHTML = json.name } } document.querySelector('button').addEventListener('click', handleClick)
img src="https://assets.aaonline.io/Module-Web/ajax/ajax.svg" height="500"/>
In this file, you'll be setting up event listeners and implementing AJAX requests using the Fetch API.
launch the server by running npm start, and then go to your browser and navigate to localhost:3000.