Skip to content

Commit d9aacff

Browse files
committed
Add client-side fetch implementation
1 parent 4c62398 commit d9aacff

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

JavaScript/4-fetch.html

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<body>
4+
<div id="message"></div>
5+
<script>
6+
7+
const message = document.getElementById('message');
8+
9+
const fetch = url => new Promise((resolve, reject) => {
10+
const xhr = new XMLHttpRequest();
11+
xhr.onreadystatechange = () => {
12+
if (xhr.readyState === XMLHttpRequest.DONE) {
13+
if (xhr.status === 200) resolve(xhr.responseText);
14+
else reject(`Status Code: ${xhr.status}`);
15+
}
16+
};
17+
xhr.open('GET', url, true);
18+
xhr.send();
19+
});
20+
21+
// Usage
22+
23+
fetch('/person')
24+
.then(body => message.innerHTML = body)
25+
.catch(err => message.innerHTML = err);
26+
27+
</script>
28+
</body>
29+
</html>

JavaScript/4-fetch.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
'use strict';
2+
3+
const fs = require('fs');
4+
const http = require('http');
5+
6+
const index = fs.readFileSync('./4-fetch.html');
7+
const person = { name: 'Marcus' };
8+
const data = JSON.stringify(person);
9+
10+
http.createServer((req, res) => {
11+
res.end(req.url === '/person' ? data : index);
12+
}).listen(8000);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy