forked from airamez/codando-live
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_06_HttpRequest.js
More file actions
95 lines (86 loc) · 3.36 KB
/
_06_HttpRequest.js
File metadata and controls
95 lines (86 loc) · 3.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
function displayResult(data) {
const output = document.getElementById('resultOutput');
output.value = JSON.stringify(data, null, 2);
console.log(data);
}
function xhrRequest() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/users', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const data = JSON.parse(xhr.responseText);
displayResult(data);
}
};
xhr.onerror = () => displayResult({ error: 'XHR request failed' });
xhr.send();
}
function fetchGetRequest() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => displayResult(data))
.catch(error => displayResult({ error: error.message }));
}
function fetchPostRequest() {
const postInput = document.getElementById('postInput').value;
try {
const jsonData = JSON.parse(postInput);
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(jsonData),
})
.then(response => {
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
})
.then(data => displayResult(data))
.catch(error => displayResult({ error: error.message }));
} catch (error) {
displayResult({ error: 'Invalid JSON input' });
}
}
async function asyncAwaitRequest() {
try {
const userResponse = await fetch('https://jsonplaceholder.typicode.com/users/1');
if (!userResponse.ok) throw new Error('Failed to fetch user');
const user = await userResponse.json();
const postsResponse = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${user.id}`);
if (!postsResponse.ok) throw new Error('Failed to fetch posts');
const posts = await postsResponse.json();
displayResult({ user, posts });
} catch (error) {
displayResult({ error: error.message });
}
}
function multiUserPostsRequest() {
// Create an array of Promises for fetching posts
const promises = [
fetch('https://jsonplaceholder.typicode.com/posts?userId=1'),
fetch('https://jsonplaceholder.typicode.com/posts?userId=2'),
fetch('https://jsonplaceholder.typicode.com/posts?userId=3')
];
// Wait for all Promises to resolve and handle results
Promise.all(promises.map(promise =>
promise.then(response => response.json())
))
.then(results => displayResult(results.flat()))
.catch(error => displayResult({ error: `Failed to fetch posts:${error}` }));
}
function clearResults() {
document.getElementById("resultOutput").value = "";
}
// Add event listeners when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('xhrButton').addEventListener('click', xhrRequest);
document.getElementById('fetchGetButton').addEventListener('click', fetchGetRequest);
document.getElementById('fetchPostButton').addEventListener('click', fetchPostRequest);
document.getElementById('asyncAwaitButton').addEventListener('click', asyncAwaitRequest);
document.getElementById('multiUserPostsButton').addEventListener('click', multiUserPostsRequest);
document.getElementById('clearResultsButton').addEventListener('click', clearResults);
});