-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
65 lines (56 loc) · 1.79 KB
/
index.html
File metadata and controls
65 lines (56 loc) · 1.79 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
<html>
<body>
<div>
<h1>Fetch API Interceptors Example</h1>
</br>
<h2>Open Console tab to check execution</h2>
</div>
</body>
<script>
// Custom fetch extension
const originalFetch = window.fetch;
// Request middleware
function requestMiddleware(url, options) {
console.log('Request Middleware');
// Modify the request options or perform any pre-processing
// For example, add headers, handle authentication, or log the request
return [url, options];
}
// Response middleware
function responseMiddleware(response) {
console.log('Response Middleware');
if (!response.ok) {
// Returns a rejected promise which will cause the control to jump to the
// nearest .catch block, where you can handle the error. In this case
// the nearest .catch block calls `errorHandling` function.
return Promise.reject(response);
}
// Handle successful response. Since `response.json()` already return a
// promise, no need to wrap inside Promise.resolve, it's redundant.
return response.json();
}
// Error handling
function errorHandling(error) {
console.log('Error Handling');
return Promise.reject(error);
}
window.fetch = function(url, options) {
const [modifiedUrl, modifiedOptions] = requestMiddleware(url, options);
return originalFetch(modifiedUrl, modifiedOptions)
.then(response => responseMiddleware(response))
.catch(error => errorHandling(error))
};
// Usage
async function fetchTodos() {
console.log('Fetch Todos');
try {
const response = await
fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log('Fetch Todos response - ', response);
} catch(error) {
console.log('Fetch Todos error - ', error);
}
}
fetchTodos();
</script>
</html>