1.下载axios插件 cnpm install axiOS -S 2.在main.js引入axios import axios from 'axios' Vue.prot
1.下载axios插件
cnpm install axiOS -S
2.在main.js引入axios
3.创建axios实例
let service = axios.create({
baseURL: baseUrl, // url = base api url + request url
withCredentials: true, // send cookies when cross-domain requests
timeout: 5000 // request timeout
})
4.请求拦截
let loading;
// 请求拦截
service.interceptors.request.use(config => {
// loding动画开启
loading = Toast.loading({
duration:10000,
message:"加载中...",
forbidClick:true,
})
//config.headers['Authorization'] = sessionStorage.getItem('token')
return config
},error =>{
console.log(error);
return Promise.reject(error)
})
5.响应拦截
// 响应拦截
service.interceptors.response.use(res =>{
// 清除loading
loading.clear()
return Promise.resolve(res)
},error =>{
loading.clear()
console.log('err'+error);
return Promise.reject(error)
})
6.抛出
// 抛出
export default service
完整代码
// 引入文件
import axios from 'axios'
import {baseUrl} from '@/config'
import {Toast} from 'vant'
// 基础配置
let service = axios.create({
baseURL: baseUrl, // url = base api url + request url
withCredentials: true, // send cookies when cross-domain requests
timeout: 5000 // request timeout
})
let loading;
// 请求拦截
service.interceptors.request.use(config => {
// loding动画开启
loading = Toast.loading({
duration:10000,
message:"加载中...",
forbidClick:true,
})
//config.headers['Authorization'] = sessionStorage.getItem('token')
return config
},error =>{
console.log(error);
return Promise.reject(error)
})
// 响应拦截
service.interceptors.response.use(res =>{
// 清除loading
loading.clear()
return Promise.resolve(res)
},error =>{
loading.clear()
console.log('err'+error);
return Promise.reject(error)
})
// 抛出
export default service
到此这篇关于javascript axios安装与封装案例详解的文章就介绍到这了,更多相关js axios安装与封装内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: JavaScript axios安装与封装案例详解
本文链接: https://lsjlt.com/news/133999.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0