Skip to content

Instantly share code, notes, and snippets.

@liuxiaomingskm
Last active February 2, 2020 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuxiaomingskm/c8b9b9c9ef3170c7b7c2b9f3a416755a to your computer and use it in GitHub Desktop.
Save liuxiaomingskm/c8b9b9c9ef3170c7b7c2b9f3a416755a to your computer and use it in GitHub Desktop.
Axios Error Handling (axios有更为精细的错误划分 error.reponse, error.request)
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<button>CLICK</button>
<section id="comments"></section>
var btn = document.querySelector("button");
var section = document.querySelector("#comments");
btn.addEventListener("click", sendRequest);
function sendRequest(){
axios.get("https://jsonplaaskjldceholder.typicode.com/comments", {
params: {
postId: 1
}
})
.then(addComments)
.catch(handleErrors)
}
function addComments(res){
res.data.forEach(function(comment){
appendComment(comment);
});
}
function appendComment (comment){
var newP = document.createElement("p");
newP.innerText = comment.email;
section.appendChild(newP);
}
function handleErrors(err) {
if (err.response) {
console.log("Problem With Response ", err.response.status);
} else if (err.request) {
console.log("Problem With Request!");
} else {
console.log('Error', err.message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment