forked from prasadyash2411/axios-crash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
237 lines (218 loc) · 5.9 KB
/
main.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
227
228
229
230
231
232
233
234
235
236
237
//AXIOS GLOBALS
axios.defaults.headers.common['X-Auth-Token']='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
// GET REQUEST
function getTodos() {
/*
axios({
method:'get',
url:'https://jsonplaceholder.typicode.com/todos',
params:{
_limit: 5
}
})
.then(res =>showOutput(res))
.catch(err =>console.error(err));
*/
//making code a little bit shorter
/*
axios.get('https://jsonplaceholder.typicode.com/todos',{
params:{_limit: 5}
})
.then(res =>showOutput(res))
.catch(err =>console.error(err));
*/
//specifying the limit in the url and we don't even have to
//specify .get its get request by default
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5',{
timeout: 5000
})
.then(res =>showOutput(res))
.catch(err =>console.error(err));
}
// POST REQUEST
function addTodo() {
/*
axios({
method:'post',
url:'https://jsonplaceholder.typicode.com/todos',
data: {
title: 'New Todo',
completed:false
}
})
.then(res=> showOutput(res))
.catch(err=>console.error(err));
*/
//making code a little bit shorter
axios.post('https://jsonplaceholder.typicode.com/todos',{
title:'New Todo',
completed:false
})
.then(res=> showOutput(res))
.catch(err=>console.error(err));
}
// PUT/PATCH REQUEST
function updateTodo() {
/*
axios.put('https://jsonplaceholder.typicode.com/todos/1',{
title:'Updated Todo',
completed:true
})
.then(res=> showOutput(res))
.catch(err=>console.error(err));
*/
axios.patch('https://jsonplaceholder.typicode.com/todos/1',{
title:'Updated Todo',
completed:true
})
.then(res=> showOutput(res))
.catch(err=>console.error(err));
}
// DELETE REQUEST
function removeTodo() {
axios.delete('https://jsonplaceholder.typicode.com/todos/1')
.then(res=> showOutput(res))
.catch(err=>console.error(err));
}
// SIMULTANEOUS DATA
function getData() {
axios.all([
axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5'),
axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5')
])
.then(axios.spread((todos,posts)=> showOutput(posts)))
.catch(err=>console.error(err));
}
// CUSTOM HEADERS
function customHeaders() {
const config={
headers:{
'Content-Type':'application/json',
Authorization:'sometoken'
}
};
axios.post('https://jsonplaceholder.typicode.com/todos',{
title:'New Todo',
completed:false
},config)
.then(res=> showOutput(res))
.catch(err=>console.error(err));
}
// TRANSFORMING REQUESTS & RESPONSES
function transformResponse() {
const options={
method:'post',
url:'https://jsonplaceholder.typicode.com/todos',
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('https://jsonplaceholder.typicode.com/todoss',{
//validateStatus: function(status){
//return status<500; //Reject only if status is greater than or equal to 500
//}
})
.then(res =>showOutput(res))
.catch(err => {
if(err.response){
//server responded with a status other than 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);
}
else{
console.error(err.message);
}
});
}
// CANCEL TOKEN
function cancelToken() {
const source=axios.CancelToken.source();
axios.get('https://jsonplaceholder.typicode.com/todoss',{
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 sent to ${config.url} at ${new Date()}`);
return config;
},
error => {
return Promise.reject(error);
}
);
// AXIOS INSTANCES
const axiosInstance=axios.create({
//other custom settings
baseURL:'https://jsonplaceholder.typicode.com'
});
//axiosInstance.get('/comments').then(res=> showOutput(res));
// 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);