forked from jsmapr1/simplifying-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.js
More file actions
93 lines (82 loc) · 1.68 KB
/
fetch.js
File metadata and controls
93 lines (82 loc) · 1.68 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
/* eslint-disable no-console, no-unused-vars, no-param-reassign */
const fetch = require('node-fetch');
const example =
// START:result
{
userId: 1,
id: 1,
title: 'First Post',
body: 'This is my first post...',
};
// END:result
// START:simple
fetch('https://jsonplaceholder.typicode.com/posts/1');
// END:simple
// START:resolve
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(data => {
return data.json();
})
.then(post => {
console.log(post.title);
});
// END:resolve
// START:catch
fetch('https://jsonplaceholder.typicode.com/pots/1')
.then(data => {
if (!data.ok) {
throw Error(data.status);
}
return data.json();
})
.then(post => {
console.log(post.title);
})
.catch(e => {
console.log(e);
});
// END:catch
// START: post
const update = {
title: 'Clarence White Techniques',
body: 'Amazing',
userId: 1,
};
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(update),
};
fetch('https://jsonplaceholder.typicode.com/posts', options).then(data => {
if (!data.ok) {
throw Error(data.status);
}
return data.json();
}).then(update => {
console.log(update);
// {
// title: 'Clarence White Techniques',
// body: 'Amazing',
// userId: 1,
// id: 101
// };
}).catch(e => {
console.log(e);
});
// END: post
function getPosts() {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then(d => {
return d.json();
});
}
function setLatestPost(element, retrievePosts) {
return retrievePosts()
.then(posts => {
console.log(posts);
element.innerHTML = posts[0].title;
});
}
export { setLatestPost };