A Pen by liuxiaomingskm on CodePen.
Last active
February 2, 2020 16:46
-
-
Save liuxiaomingskm/c8b9b9c9ef3170c7b7c2b9f3a416755a to your computer and use it in GitHub Desktop.
Axios Error Handling (axios有更为精细的错误划分 error.reponse, error.request)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> | |
<button>CLICK</button> | |
<section id="comments"></section> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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