GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — JavaScript fetch - fetching resources asynchronously in JavaScript JavaScript fetchlast modified last modified October 18, 2023 In this article we show how to fetching resources asynchronously in JavaScript using the fetch API. The fetch function
The let promise = fetch(url, [options])
If we do not provide the When we get the response we can check HTTP status or the headers, but we don't have the body yet. To get the body of the response, we call one of the following methods:
The JavaScript fetch simple example
In the first example, we generate a simple asynchronous GET request with the
<script>
fetch('http://time.jsontest.com')
.then(res => res.json())
.then((data) => {
console.log(data);
}).catch(err => console.error(err));
</script>
In this example, we use callbacks. The Object { date: "01-26-2021", milliseconds_since_epoch: 1611661589016,
time: "11:46:29 AM" }
We check the console output in our browser. <script>
async function doRequest() {
let url = 'http://time.jsontest.com';
let res = await fetch(url);
if (res.ok) {
let json = await res.json();
return json;
} else {
return `HTTP error: ${res.status}`;
}
}
doRequest().then(data => {
console.log(data);
});
</script>
In this example we use the if (res.ok) {
The JS fetch GET requestThe following example creates a simple GET request and processes the result as text. <script>
async function doRequest() {
let url = 'http://webcode.me';
let res = await fetch(url);
if (res.ok) {
let text = await res.text();
return text;
} else {
return `HTTP error: ${res.status}`;
}
}
doRequest().then(data => {
console.log(data);
});
</script>
We get the contents of the webcode.me webpage. let url = 'http://webcode.me'; let res = await fetch(url);
The let text = await res.text(); We get the body from the request as plain text. <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My html page</title>
</head>
<body>
<p>
Today is a beautiful day. We go swimming and fishing.
</p>
<p>
Hello there. How are you?
</p>
</body>
</html>
This is the output that we can see in the browser console window. JS fetch GET request with query parametersIn the following example, we append some query parameters to the URL. <script>
async function doRequest() {
let url = new URL('http://httpbin.org/get');
let params = {'name': 'John Doe', 'occupation': 'John Doe'};
url.search = new URLSearchParams(params);
let res = await fetch(url);
if (res.ok) {
let text = await res.text();
return text;
} else {
return `HTTP error: ${res.status}`;
}
}
doRequest().then(data => {
console.log(data);
});
</script>
We use the {
"args": {
"name": "John Doe",
"occupation": "John Doe"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.5",
"Host": "httpbin.org",
"Origin": "null",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
"X-Amzn-Trace-Id": "Root=1-600ff33e-71b89c984ad2878035263a8b"
},
...
"url": "http://httpbin.org/get?name=John+Doe&occupation=John+Doe"
}
We get this output from the JS fetch get imageThe following example retrieves an image and displays it on the page. <script>
async function doRequest() {
let url = 'https://dummyimage.com/100x100/499deb/fff';
let res = await fetch(url);
let blob = await res.blob();
return blob;
}
doRequest().then(blob => {
let img = document.createElement('img');
document.body.append(img);
img.src = URL.createObjectURL(blob);
});
</script>
The example uses the let blob = await res.blob();
To get the image data, we call the let img = document.createElement('img');
document.body.append(img);
We programmatically create the img.src = URL.createObjectURL(blob);
We create the image with the JS fetch JSON POST requestThe following example generates a POST request with JSON data. <script>
async function doRequest() {
let url = 'http://httpbin.org/post';
let data = {'name': 'John Doe', 'occupation': 'John Doe'};
let res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (res.ok) {
// let text = await res.text();
// return text;
let ret = await res.json();
return JSON.parse(ret.data);
} else {
return `HTTP error: ${res.status}`;
}
}
doRequest().then(data => {
console.log(data);
});
</script>
The request is sent to http://httpbin.org/post. let data = {'name': 'John Doe', 'occupation': 'John Doe'};
This is the data to be sent. let res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
We set the let ret = await res.json(); return JSON.parse(ret.data); We get the data back as JSON string and parse it into the JSON object. Object { name: "John Doe", occupation: "John Doe" }
JS fetch POST form dataIn the following example, we generate a POST request with form data.
With <script>
async function doRequest() {
let url = 'http://httpbin.org/post';
let formData = new FormData();
formData.append('name', 'John Doe');
formData.append('occupation', 'gardener');
let res = await fetch(url, {
method: 'POST',
body: formData,
});
if (res.ok) {
let text = await res.text();
return text;
} else {
return `HTTP error: ${res.status}`;
}
}
doRequest().then(data => {
console.log(data);
});
</script>
To produce form data in the appropriate format, we use the {
"args": {},
"data": "",
"files": {},
"form": {
"name": "John Doe",
"occupation": "gardener"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.5",
"Content-Length": "305",
"Content-Type": "multipart/form-data; ...
"Host": "httpbin.org",
"Origin": "null",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0",
"X-Amzn-Trace-Id": "Root=1-600ff649-4cd21c6a503e694211f73b0c"
},
"json": null,
...
"url": "http://httpbin.org/post"
}
SourceIn this article we have worked with the JavaScript fetch API. AuthorMy name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |