Skip to content

Instantly share code, notes, and snippets.

@geekdaniels
Forked from redsoxfan2499/axios-examples.js
Created December 13, 2022 07:55
Show Gist options
  • Save geekdaniels/ea5b5364df9ecdc812de8c8da1fe4ff5 to your computer and use it in GitHub Desktop.
Save geekdaniels/ea5b5364df9ecdc812de8c8da1fe4ff5 to your computer and use it in GitHub Desktop.
// 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
// }
// })
axios
.get("https://jsonplaceholder.typicode.com/todos?_limit=5")
.then(res => showOutput(res))
.catch(err => console.error(err));
}
// POST REQUEST
function addTodo() {
axios
.post("https://jsonplaceholder.typicode.com/todos", {
data: { title: "Test Todo", completed: false }
})
.then(res => showOutput(res))
.catch(err => console.error(err));
}
// PUT/PATCH REQUEST
function updateTodo() {
axios
.patch("https://jsonplaceholder.typicode.com/todos/2", {
title: "Updated Todo",
completed: false
})
.then(res => showOutput(res))
.catch(err => console.error(err));
}
// DELETE REQUEST
function removeTodo() {
axios
.delete("https://jsonplaceholder.typicode.com/todos/2")
.then(res => showOutput(res))
.catch(err => console.error(err));
}
// SIMULTANEOUS DATA
function getData() {
// axios
// .all([
// axios.get("https://jsonplaceholder.typicode.com/todos"),
// axios.get("https://jsonplaceholder.typicode.com/posts")
// ])
// .then(res => {
// console.log(res[0]);
// console.log(res[1]);
// showOutput(res[1]);
// })
// .catch(err => console.error(err));
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: "Test 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: "Hey Now"
},
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/todoxs")
.then(res => showOutput(res))
.catch(err => {
if (err.response) {
// Server responsed with a status other than 200 range
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
// Request was made but no reponse
console.error(err.request);
} else {
console.error(err.message);
}
});
}
// ERROR HANDLING
function errorHandlingTwo() {
axios
.get("https://jsonplaceholder.typicode.com/todoxs", {
validateStatus: function(status) {
return status < 500; // reject only is status if 500
}
})
.then(res => showOutput(res))
.catch(err => {
if (err.response) {
// Server responsed with a status other than 200 range
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
// Request was made but no reponse
console.error(err.request);
} else {
console.error(err.message);
}
});
}
// CANCEL TOKEN
function cancelToken() {
const source = axios.CancelToken.source();
axios
.get("https://jsonplaceholder.typicode.com/todos", {
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().getTime()}`
);
return config;
},
error => {
return Promise.reject(error);
}
);
// AXIOS Using TimeOuts
function timeouts() {
axios
.get("https://jsonplaceholder.typicode.com/todos?_limit=5", { timeout: 5 })
.then(res => showOutput(res))
.catch(err => console.error(err));
}
// AXIOS INSTANCES
// const axiosInstance = axios.create({
// 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("timeout").addEventListener("click", timeouts);
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);
document.getElementById("errortwo").addEventListener("click", errorHandlingTwo);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous"
/>
<title>Axios Crash Course</title>
</head>
<body>
<div class="container my-5">
<div class="text-center">
<h1 class="display-4 text-center mb-3">Axios Crash Course</h1>
<button class="btn btn-primary my-3" id="get">GET</button>
<button class="btn btn-info" id="post">POST</button>
<button class="btn btn-warning" id="update">PUT/PATCH</button>
<button class="btn btn-danger" id="delete">DELETE</button>
<button class="btn btn-primary my-3" id="timeout">Timeout</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="errortwo">
Error Handling Two
</button>
<button class="btn btn-secondary" id="cancel">
Cancel
</button>
</div>
<hr />
<div id="res"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<script src="main.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment