封装axios
- src 目录中新建utils文件夹
- utils文件夹中建立
http.js 文件
import axios from 'axios'
import { Toast } from 'vant';
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_URL,
withCredentials: true,
timeout: 5000
})
service.interceptors.request.use(config=>{
Toast.loading({
message: '加载中...',
forbidClick: true,
});
return config
},err=>{
throw Error(err)
})
service.interceptors.response.use(response=>{
Toast.clear()
const res = response.data
if (res.status && res.status !== 200) {
if (res.status === 401) {
Toast.loading({
message: '登录超时,请从新登录',
forbidClick: true,
});
}
return Promise.reject(res || 'error')
} else {
return res.data
}
},err=>{
return Promise.reject(err)
})
export default service
封装api 函数
- utils文件夹中新建
api.js
import service from './http';
export function getHome(data){
return service.get('/home',data)
}
export function lunbo(data){
return service.get('/home/shejishi',data)
}
api函数调用方法
import {getHome,lunbo} from '../utils/api';
export default {
name: 'Home',
created(){
getHome({}).then(res=>{
console.log(res)
})
lunbo({}).then(res=>{
console.log(res)
})
}
}
|