Repository navigation
Expand file tree
/
Copy pathfetch.js
More file actions
73 lines (62 loc) · 1.82 KB
/
Copy pathfetch.js
File metadata and controls
73 lines (62 loc) · 1.82 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
// 4 ways to call api - XMLHttpRequest, fetch, axios, jquery
// fetch() has replaced XMLHttpRequest
// fetch() - global method for making HTTP Request
// 2 ways to call - then, async await
// + fetch() is easy to use compare to XMLHttpRequest
// + fetch() returns a promise
// - returned promise can only handle network error
// - does not support all the older browser
// method for making HTTP Request
const makeRequest = async (url, config) => {
const res = await fetch(url, config);
if (!res.ok) {
const message = `Error : ${res.status}`;
throw new Error(message);
}
const data = await res.json();
return data;
};
const deleteData = () => {
makeRequest("https://jsonplaceholder.typicode.com/posts/1", {
method: "DELETE",
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
};
deleteData();
// const updateData = () => {
// makeRequest("https://jsonplaceholder.typicode.com/posts/1", {
// method: "PATCH",
// body: JSON.stringify({
// title: "foomaraarrara",
// }),
// headers: {
// "Content-type": "application/json; charset=UTF-8",
// },
// })
// .then((res) => console.log(res))
// .catch((err) => console.log(err));
// };
// updateData();
// const sendData = () => {
// makeRequest("https://jsonplaceholder.typicode.com/posts", {
// method: "POST",
// body: JSON.stringify({
// title: "foo",
// body: "bar",
// userId: 1,
// }),
// headers: {
// "Content-type": "application/json; charset=UTF-8",
// },
// })
// .then((res) => console.log(res))
// .catch((err) => console.log(err));
// };
// sendData();
// const getData = () => {
// makeRequest("https://jsonplaceholder.typicode.com/posts")
// .then((res) => console.log(res))
// .catch((err) => console.log(err));
// };
// getData();