Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Complete Functionality of AXIOS Capabilities coded #18

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 4 additions & 12 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,10 @@ <h1 class="display-4 text-center mb-3">Axios Crash Course</h1>
<button class="btn btn-warning" id="update">PUT/PATCH</button>
<button class="btn btn-danger" id="delete">DELETE</button>
<button class="btn btn-secondary" id="sim">Sim Requests</button>
<button class="btn btn-secondary" id="headers">
Custom Headers
</button>
<button class="btn btn-secondary" id="transform">
Transform
</button>
<button class="btn btn-secondary" id="error">
Error Handling
</button>
<button class="btn btn-secondary" id="cancel">
Cancel
</button>
<button class="btn btn-secondary" id="headers">Custom Headers</button>
<button class="btn btn-secondary" id="transform">Transform</button>
<button class="btn btn-secondary" id="error">Error Handling</button>
<button class="btn btn-secondary" id="cancel">Cancel</button>
</div>
<hr />
<div id="res"></div>
Expand Down
160 changes: 148 additions & 12 deletions main.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,188 @@
//AXIOS GLOBALS
axios.defaults.headers.common['X-Auth-Token'] ='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';

// GET REQUEST
function getTodos() {
console.log('GET Request');
// axios({
// method:'get',
// url:'https://jsonplaceholder.typicode.com/todos',
// params:{
// _limit:5
// }
// })
// .then((response) => showOutput(response))
// .catch((err)=>console.log(err));
// console.log('GET Request');

////// Shortening the above request /////////

axios
.get('https://jsonplaceholder.typicode.com/todos?_limit=5',{timeout: 2000})
.then((response) => showOutput(response))
.catch((err) => console.log(err));

//console.log('GET Request');
}

// POST REQUEST
// POST REQUEST -- //Gives Output with new Todo and ID attached from server
function addTodo() {
console.log('POST Request');
axios
.post('https://jsonplaceholder.typicode.com/todos',{title:'New Todo',completed:false})
.then((response) => showOutput(response))
.catch((err)=>console.log(err));

//console.log('POST Request');
}

// PUT/PATCH REQUEST
function updateTodo() {
console.log('PUT/PATCH Request');
// axios
// .put('https://jsonplaceholder.typicode.com/todos/1', { //Needs id of ToDo to UPDATE -- Replace Everything
// title: 'Updated Todo', completed: true //Gives Output with new Todo and ID attached from server
// })
// .then((response) => showOutput(response))
// .catch((err) => console.log(err))

axios
.patch('https://jsonplaceholder.typicode.com/todos/1', { //Needs id of ToDo to UPDATE -- Replace Everything
title: 'Updated Todo', completed: true //Gives Output with new Todo and ID attached from server
})
.then((response) => showOutput(response))
.catch((err) => console.log(err))

//console.log('PUT/PATCH Request');
}

// DELETE REQUEST
function removeTodo() {
console.log('DELETE Request');

axios
.delete('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => showOutput(response))
.catch((err) => console.log(err))

//console.log('DELETE Request');
}

// SIMULTANEOUS DATA
function getData() {
console.log('Simultaneous Request');

axios.all([
axios.get('https://jsonplaceholder.typicode.com/todos'),
axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5')
]).then(axios.spread((todos,posts)=>showOutput(posts))) //gives ability to give Var names to axios.all array Promise outputs
.catch((err)=>console.error(err));

//console.log('Simultaneous Request');
}

// CUSTOM HEADERS
function customHeaders() {
console.log('Custom Headers');
const config={
headers:{
'Content-Type':'application/json',
Authorization:'someJWTtoken'
}
}

axios
.post('https://jsonplaceholder.typicode.com/todos', {
title: 'New Todo', completed: false //Gives Output with new Todo and ID attached from server
},config
)
.then((response) => showOutput(response))
.catch((err) => console.log(err))
}

// TRANSFORMING REQUESTS & RESPONSES
function transformResponse() {
console.log('Transform Response');
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)); //Making axios request with options object holding method url data etc

//console.log('Transform Response');
}

// ERROR HANDLING
function errorHandling() {
console.log('Error Handling');
axios //or axios('https://jsonplaceholder.typicode.com/todoss')
.get('https://jsonplaceholder.typicode.com/todoss',{
// validateStatus: function(status){
// return status<500; //Reject only if Status>=500
// }
})
.then((response) => showOutput(response))
.catch((err) => {
if(err.response){
//Server response status 200
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 there's no response
console.error(err.request);
}
else{
console.error(err.message);
}
}
});

//console.log('Error Handling');
}

// CANCEL TOKEN
function cancelToken() {
console.log('Cancel Token');
}
const source = axios.CancelToken.source();
axios //or axios.get
.get('https://jsonplaceholder.typicode.com/todos',{
cancelToken: source.token
})
.then((response) => showOutput(response))
.catch(thrown=>{
if(axios.isCancel(thrown)){
console.log('Request Canceled',thrown.message)
}
});
if(true){
source.cancel('Request Cancelled!')
}

// INTERCEPTING REQUESTS & RESPONSES
//console.log('Cancel Token');
}

// INTERCEPTING REQUESTS & RESPONSES -- To Track/intercept requests - Log type URL and Time when the request was made
axios.interceptors.request.use(config=>{
console.log(`${config.method.toUpperCase()} request sent to ${config.url} at ${new Date().getTime()}`);
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)).catch(e=>console.log(e));


// Show output in browser
function showOutput(res) {
document.getElementById('res').innerHTML = `
Expand Down