适合初学者配置使用,只封装了get和post其他类似patch、put和axios.all()的方法得自己动手了,如果遇到项目有多个baseURL的这套封装就显得很不灵活,但一般是不会遇到的,这套简单的封装总的来说够用了,且非常实用。
新建https.ts复制下面代码进去引用即可,如果是js版本的把url:any, param:any后面的:any去掉。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| import axios from 'axios' import qs from 'qs'
axios.defaults.timeout = 5000; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; axios.defaults.baseURL = 'http://192.168.0.6:9000';
axios.interceptors.request.use((config) => { if (config.method === 'post') { config.data = qs.stringify(config.data); } return config; }, (error) => { console.log('错误的传参') return Promise.reject(error); });
axios.interceptors.response.use((res) => { if (!res.data.success) { return Promise.resolve(res); } return res; }, (err) => { if (err.response.status == 504 || err.response.status == 404) { console.log("服务器被吃了⊙﹏⊙∥") } else if (err.response.status == 403) { console.log("权限不足,请联系管理员!") } else { console.log("未知错误") } return Promise.reject(err); });
export function myPost(url: any, params: any) { return new Promise((resolve, reject) => { axios.post(url, params) .then(response => { resolve(response); }, err => { reject(err); }) .catch((error) => { reject(error) }) }) }
export function myGet(url: any, param: any) { return new Promise((resolve, reject) => { axios.get(url, { params: param }) .then(response => { resolve(response) }, err => { reject(err) }) .catch((error) => { reject(error) }) }) } export default { myPost, myGet, }
|
#axios使用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <template> <div class="home"></div> </template>
<script lang="ts"> import { Component, Vue } from "vue-property-decorator"; import https from "../https"; @Component({ data() { return { dataList: [], }; }, created() { console.log(https); let param = { pageNo: 1, pageSize: 20, }; https .myGet("/case/lists", param) .then((res) => { console.log(res.data.dataList); this.dataList = res.data.dataList; }) .catch((err) => console.log(err)); }, }) export default class Home extends Vue {} </script>
|
#axios拦截器指定页面添加token
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| axios.interceptors.request.use( function (config) { if (config.url !== "login") { config.headers["Authorization"] = localStorage.getItem("token"); }
return config; }, function (error) { return Promise.reject(error); }, );
|
接口请求错误处理(status !== 200),应用场景:全局拦截报错信息跳转指定页面(login、home)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| axios.interceptors.response.use( (res) => { if (!res.data.success) { return Promise.resolve(res); } return res; }, (error) => { console.log("网络异常"); console.log(error.response.status);
return Promise.reject(error); }, );
|