一、什么是 axios?
Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中,
二、引入方式
使用: npm install axios
使用 :bower install axios
使用: cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
三、案例
使用get方法
<input type="button" value="get請求" class="get">
<input type="button" value="post請求" class="post">
<!-- 官網提供的 axios 在線地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script /*
介面1:隨機笑話
請求地址:https://autumnfish.cn/api/joke/list
請求方法:get
請求引數:num(笑話條數,數字)
回應內容:隨機笑話
*/
document.querySelector(".get").onclick = function () {
// 用get請求地址
axios.get("https://autumnfish.cn/api/joke/list?num=6")
.then(function (response) {
console.log(response);
},function(err){
console.log(err);
})
}
使用post方法
/*
介面:用戶注冊
請求地址:https://autumnfish.cn/api/user/reg
請求方法:post
請求引數:username(用戶名,字串)
回應內容:注冊成功或失敗
*/
<script>
document.querySelector(".post").onclick = function () {
//用post請求地址
axios.post("https://autumnfish.cn/api/user/reg",{username:"鹽焗西蘭花"})
.then(function(response){
console.log(response);
console.log(this.skill);
},function (err) {
console.log(err);
})
}
</script>
請求別名的方法
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.options(url[, config])
- axios.post(url[, data[, config]])
- axios.put(url[, data[, config]])
- axios.patch(url[, data[, config]])
注意
在使用別名方法時, url、method、data 這些屬性都不必在配置中指定,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/294241.html
標籤:其他
