forked from bradtraversy/axios-crash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstart.js
226 lines (195 loc) · 6.85 KB
/
start.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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
// Globals- with globals you can send a header value with every request, this comes in handy with tokens and authentication
axios.defaults.headers.common['X-Auth-Token'] = 'sometoken'
//token will appear in the config after any request//
// GET REQUEST-1st method is the long form, second method is shorthand
// function getTodos() {
// axios({
// method: 'get'
// url:'zillow-com1.p.rapidapi.com'//this is where you put the url for the api, this returns a promise//
// params: {
// _limit:5
// }
// })
// .then (res => showOutput(res)); //res is response, for error handling with promises you can add catch//
// .catch (err => console.error(err));
// }//res.data is always going to be the data that is returned//
axios.get( 'zillow-com1.p.rapidapi.com?_limit=5', {timeout:5}) //you can add a method to axios with a dot, you don't have to add.get for the get request but it is cleaner to do so//
.then(res => showOutput(res))
.catch(err => console.error(err));
// POST REQUEST- 1st method is the long form, second method is shorthand
// function addTodo() {
// function getTodos() {
// axios({
// method: 'get'
// url:'zillow-com1.p.rapidapi.com'//this is where you put the url for the api, this returns a promise//
// data: {
// title:'New Todo',
// completed:false
// }
// })
// .then (res => showOutput(res)); //res is response, for error handling with promises you can add catch//
// .catch (err => console.error(err));
// }//res.data is always going to be the data that is returned//
function addTodo(){
axios('zillow-com1.p.rapidapi.com',{
title:'New Todo',
completed:false
})
.then(res => showOutput(res))
.catch(err => console.error(err));
}
// PUT/PATCH REQUEST- PUT is meant to replace the entire resource, PATCH will update it incrementally
function updateTodo() {
axios
.put('zillow-com1.p.rapidapi.com',{ //if you use a PATCH request instead it will just change what is specified and not the whole resource//
title:'Updated Todo',//here you'll put in the parameter that you want to add//
completed:true
})
.then(res => showOutput(res))
.catch(err => console.error(err));
}
// DELETE REQUEST-
function removeTodo() {
function updateTodo() {
axios
.delete('zillow-com1.p.rapidapi.com/todo/1',{ //if you use a PATCH request instead it will just change what is specified and not the whole resource//
.then(res => showOutput(res))//don't need to pass any data in because we're just deleting it//
.catch(err => console.error(err));
}
}
// SIMULTANEOUS DATA- axios.all will take in an array of requests and when all of the promises are fulfilled we will get our response//
function getData(){
axios.all([
axios.get('zillow-com1.p.rapidapi.com/todos_limit=5'),
axios.get('zillow-com1.p.rapidapi.com/posts_limit=5')
])
.then(res => {
console.log(res[0]);
console.log(res[1]);
showOutput(res[1]))
.catch(err => console.error(err))
}
// CUSTOM HEADERS- have to do this with tokens, like json tokens
function customHeaders() {
const config = {
headers: {
'Content-Type':'application/json'
Authorization: 'sometoken'
}
}
function addTodo(){
axios('zillow-com1.p.rapidapi.com',{
title:'New Todo',
completed:false
},
config
)
.then(res => showOutput(res))
.catch(err => console.error(err));
}
}
// TRANSFORMING REQUESTS & RESPONSES- can transform your reponse or requests in certain ways
function transformResponse() {
const options = {
method:'post'
url:'zillow-com1.p.rapidapi.com',
data:{
title:'Hello World'
},
transformResponse:axios.defaults.transformResponse.concat(data => {
data.title = data.title.toUpperCase();
return data;
})
}
axios(options).then(res => showOutput(res))
}
// ERROR HANDLING-
function errorHandling() {
axios.get( 'zillow-com1.p.rapidapi.com') //you can add a method to axios with a dot, you don't have to add.get for the get request but it is cleaner to do so//
.then(res => showOutput(res))
.catch(err => {
if(err.response)
//server responseded with a status other than the 200 range//
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
if(err.response.status===404){
alert('Error, Page Not Found')
}
}else if(err.request){
//Request was made but no response
console.error(err.request);
}
}
// CANCEL TOKEN
function cancelToken() {
const source = axios.CancelToken.source();
axios
.get( 'zillow-com1.p.rapidapi.com'{ , //you can add a method to axios with a dot, you don't have to add.get for the get request but it is cleaner to do so//
cancelToken:source.token
})
.then(res => showOutput(res))
.catch(thrown =>
if (axios.isCancel(thrown)){
console.log('Request Canceled', thrown.message);
}
});
if (true) {
source.cancel('Request canceled!');
}
// INTERCEPTING REQUESTS & RESPONSES
axios.interceptors.request.use(config =>{
console.log(`${config.method.toUpperCase()} request send to ${config.url} at ${new Date ().getTime()}`)
return config
}, error => {
return Promise.reject(error)
});
// AXIOS INSTANCES- before we were talking about axios as an object
const axiosInstance = axios.create({
baseURL: 'zillow-com1.p.rapidapi.com'
});
axiosInstance.get('/comments').then(res => showOutput)
// Show output in browser
function showOutput(res) {
document.getElementById('res').innerHTML = `
<div class="card card-body mb-4">
<h5>Status: ${res.status}</h5>
</div>
<div class="card mt-3">
<div class="card-header">
Headers
</div>
<div class="card-body">
<pre>${JSON.stringify(res.headers, null, 2)}</pre>
</div>
</div>
<div class="card mt-3">
<div class="card-header">
Data
</div>
<div class="card-body">
<pre>${JSON.stringify(res.data, null, 2)}</pre>
</div>
</div>
<div class="card mt-3">
<div class="card-header">
Config
</div>
<div class="card-body">
<pre>${JSON.stringify(res.config, null, 2)}</pre>
</div>
</div>
`;
}
// Event listeners
document.getElementById('get').addEventListener('click', getTodos);
document.getElementById('post').addEventListener('click', addTodo);
document.getElementById('update').addEventListener('click', updateTodo);
document.getElementById('delete').addEventListener('click', removeTodo);
document.getElementById('sim').addEventListener('click', getData);
document.getElementById('headers').addEventListener('click', customHeaders);
document
.getElementById('transform')
.addEventListener('click', transformResponse);
document.getElementById('error').addEventListener('click', errorHandling);
document.getElementById('cancel').addEventListener('click', cancelToken);