Fetch API
The Fetch API is a interface for making http requests using javascript in the browser and with node version +18. If you are familiar with the XMLHttpRequest or ajax() from jQuery this will feel familiar.
Concepts
The fetch api is built on promises and returns a Response
object that will need further processing depending on the data parsing you want. The fetch()
function takes two arguments, the request URL and the parameters. Then returns a Response
object that will further process your data.
Usage
Here is a simple example of a fetch request to an RSS feed. The RSS feed is in plain text so we process it using the response.text()
method. There is also .json()
, .blob()
, .formData()
and .arrayBuffer()
.
1fetch('https://decode.sh/rss")
2 .then((response) => response.text())
3 .then((data) => console.log(data));
Fetching an image
When fetching binary data, like an image, you will want to convert it to a blob. Then you can create an object URL and use it like a file.
1const image = document.querySelector("#image");
2fetch("https://decode.sh/favicon.png")
3 .then((response) => response.blob())
4 .then((blob) => {
5 const objectURL = URL.createObjectURL(blob);
6 image.src = objectURL;
7 });
Adding Parameters
Along with the URL, fetch takes an options parameter, this allows you to set headers and make POST requests. Here's a breakdown of what can be added to the options.
- method
- The request method (GET or POST).
- headers
- Any headers you want to include.
- body
- The body you want to send. Can be a Blob, ArrayBuffer, TypedArray, DataView, FormData, URLSearchParams, a string object or literal, or a ReadableStream
- mode
- The request mode you want to use i.e. (cors, no-cors...)
- credentials
- Controls what the browser does with credentials.
For a more exhaustive list of fetch parameters see: MDN
Fetch POST Request
Here is a basic POST request example, it is broken out into a function that can be reused and returns the Response
object that the fetch
function returns.
Check out: HTTP Headers Basics
1async function postData(url = "", data = {}) {
2 // Default options are marked with *
3 const response = await fetch(url, {
4 method: "POST", // *GET, POST, PUT, DELETE, etc.
5 mode: "cors", // no-cors, *cors, same-origin
6 cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
7 credentials: "same-origin", // include, *same-origin, omit
8 headers: {
9 "Content-Type": "application/json",
10 Authorization: token,
11 // 'Content-Type': 'application/x-www-form-urlencoded',
12 },
13 redirect: "follow", // manual, *follow, error
14 referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
15 body: JSON.stringify(data), // body data type must match "Content-Type" header
16 });
17 return response;
18}
19
20// NOTE: this URL is not a real URL
21postDate("https://decode.sh/post/example", {
22 test: "Hello",
23})
24 .then((res) => res.json())
25 .then((data) => {
26 console.log(data);
27 });