-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path30_fetch.js
141 lines (126 loc) · 4.13 KB
/
30_fetch.js
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/**
* ========================================================
* Fetch API
* ========================================================
* The Fetch API provides a modern, promise-based mechanism for making HTTP requests
* in the browser and is also available in Node.js via third-party packages.
*/
/**
* ========================================================
* 1. Basic GET Request
* ========================================================
* A simple GET request can be made by passing a URL to `fetch()`. The method returns a Promise
* that resolves to the Response object representing the completed request.
*/
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Fetch error:", error));
/**
* ========================================================
* 2. Basic POST Request
* ========================================================
* For POST requests, specify the HTTP method, headers, and body.
*/
const postData = {
title: "foo",
body: "bar",
userId: 1,
};
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(postData),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error("Fetch error:", error));
/**
* ========================================================
* Nuances and Advanced Use-Cases
* ========================================================
*/
/**
* 1. Custom Headers
* -----------------
* To send custom headers, create a Headers object and append the headers you need.
*/
const customHeaders = new Headers();
customHeaders.append("Authorization", "Bearer YOUR_ACCESS_TOKEN");
fetch("https://api.example.com/data", { headers: customHeaders })
.then((response) => response.json())
.then((data) => console.log(data));
/**
* 2. Handling Timeouts
* --------------------
* Fetch does not have a built-in timeout feature. You can implement it using Promise.race().
*/
const timeoutFetch = (url, options, timeout = 3000) => {
return Promise.race([
fetch(url, options),
new Promise((_, reject) => setTimeout(() => reject(new Error("Fetch timeout")), timeout)),
]);
};
/**
* 3. Request and Response Metadata
* --------------------------------
* Request and Response objects contain metadata like status, headers, etc.
*/
fetch("https://jsonplaceholder.typicode.com/todos/1").then((response) => {
console.log(response.status); // HTTP status code
console.log(response.headers.get("Content-Type")); // Content-Type header
});
/**
* 4. Manual Redirects
* -------------------
* Fetch allows you to manually handle redirects by setting the redirect option.
*/
fetch("https://example.com", { redirect: "manual" }).then((response) => {
// Handle manual redirects here
});
/**
* 5. Abort Request
* ----------------
* A fetch request can be aborted using the AbortController API.
*/
const controller = new AbortController();
const { signal } = controller;
fetch("https://example.com", { signal }).catch((error) => {
if (error.name === "AbortError") {
console.log("Fetch aborted");
}
});
// To abort the request
controller.abort();
/**
* 6. Streaming
* ------------
* Fetch API supports streaming of data using Response.body, which is a ReadableStream.
*/
fetch("https://example.com/large-file").then((response) => {
const reader = response.body.getReader();
// Handle streaming here
});
/**
* 7. FormData
* -----------
* FormData API can be used with fetch to easily upload files or send form data.
*/
const formData = new FormData();
formData.append("key", "value");
fetch("https://example.com/upload", {
method: "POST",
body: formData,
});
/**
* 8. CORS and Fetch
* -----------------
* Fetch is CORS-aware. To make requests to another origin, the server must include the proper CORS headers.
*/
/**
* 9. Fetch vs. Axios
* ------------------
* Axios is a popular HTTP client with features like built-in timeout and automatic JSON parsing, which Fetch lacks by default.
*/