<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue_3.2.36_vue.global.js"></script>
<script src="js/axios_0.27.2_axios.js"></script>
</head>
<body>
<div id="app">
<h1>網(wǎng)站列表</h1>
<ul>
<li v-for="site in sites">{{ site.name }}</li>
</ul>
<img id="image" :src="image" alt="">
</div>
<script>
// 創(chuàng)建實例時設(shè)置默認的配置
var instance = axios.create({
baseURL: "https://www.baidu.com/api"
})
// 在實例創(chuàng)建后修改默認值
instance.defaults.headers.common["Authorization"] = "123789"
// 添加請求攔截器
// 在發(fā)送請求之前做些什么
instance.interceptors.request.use(function (config) {
console.log("請求前執(zhí)行了")
return config
})
// 對響應(yīng)數(shù)據(jù)做點什么
instance.interceptors.response.use(function (resp) {
console.log("對響應(yīng)數(shù)據(jù)做了處理")
return resp
})
const app = Vue.createApp({
data() {
return {
sites: [],
image: ""
}
},
mounted() {
// 直接url添加參數(shù)
// axios.get("/info?idx=110")
// 通過params添加參數(shù)
/*
axios.get("/info", {
"params": {
"idx": 120
}
})
*/
// post傳參
/*
axios.post("/info", {
"firstName": "My",
"lastName": "YaNan"
})
.then((res) => {
this.sites = res.data.data.sites
console.log(res)
})
.catch(function (error) {
console.log(error)
})
*/
// 一次發(fā)送多個請求
/*
axios.all([this.getUserAccount(), this.getUserPermission()])
.then(axios.spread(function (acct, perms) {
console.log(acct.data.data)
console.log(perms.data.data)
}))
.catch(function (error) {
console.log(error)
})
*/
// 可以通過向axios傳遞相關(guān)配置來創(chuàng)建請求
// 001-請求圖片
/*
axios({
method: "post",
url: "/img",
responseType: "blob"
})
.then((response) => {
const imageBlob = new Blob([response.data], {type: response.headers['content-type']});
// 創(chuàng)建一個圖片URL,用于顯示圖片
const imageUrl = URL.createObjectURL(imageBlob);
// 使用imageUrl來顯示圖片,例如將它設(shè)置為<img>元素的src屬性
this.image = imageUrl
})
.catch(function (err) {
console.log(err)
})
*/
// 使用cancel token取消請求
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
// 及簡get請求
instance.get("info", {
cancelToken: source.token
})
.then((res) => {
console.log(res)
})
// 錯誤處理
.catch(function (error) {
if (axios.isCancel(error)) {
console.log("request cancled", error.message)
}else if (error.response){
console.log("狀態(tài)碼不是2xx")
console.log(error.response.data)
console.log(error.response.status)
console.log(error.response.headers)
}else {
console.log(error.message)
}
})
// 取消請求(message 參數(shù)是可選的)
source.cancel('Operation canceled by the user.')
},
methods: {
getUserAccount: function () {
return axios.get("/userAccount")
},
getUserPermission: function () {
return axios.get("/userPermission")
}
}
})
const vm = app.mount("#app")
</script>
</body>
</html>
文章來源地址http://www.zghlxwxcb.cn/news/detail-731676.html
文章來源:http://www.zghlxwxcb.cn/news/detail-731676.html
到了這里,關(guān)于axios的各種請求方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!