为aixos配置统一请求地址,统一请求头等。
封装
在src
下新建axios/axios.js
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| import axios from 'axios'; import router from "../router" import Tools from '@/components/Tools/index'; import store from '../store'
let token = ''; axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
axios.interceptors.request.use( config => { let api_token = JSON.parse(sessionStorage.getItem('api_token')!) if (api_token) { token = api_token } config.headers.common['Authorization'] = 'Bearer ' + token; return config; }, error => { return Promise.reject(error); } );
axios.interceptors.response.use( response => { return response; }, error => { return Promise.resolve(error.response); } ); axios.defaults.baseURL = process.env.VUE_APP_BASEURL
axios.defaults.headers.post["Content-Type"] = "application/json"; axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest"; axios.defaults.headers.put["Content-Type"] = "application/json"; axios.defaults.headers.put["X-Requested-With"] = "XMLHttpRequest"; axios.defaults.headers.delete["Content-Type"] = "application/json"; axios.defaults.headers.delete["X-Requested-With"] = "XMLHttpRequest"; axios.defaults.timeout = 10000; function checkStatus(response ) { return new Promise((resolve, reject) => { if ( response && (response.status === 200 || response.status === 304 || response.status === 400) ) { resolve(response.data); } else { reject({ status: response.status, message: response.data.message, error: response.data.errors[Object.keys(response.data.errors)[0]][0] }); } }); } export default { post(url, params) { return axios({ method: "post", url, data: params }).then(response => { return checkStatus(response); }); }, get(url, params) { return axios({ method: "get", url, params }).then(response => { return checkStatus(response); }); }, put(url, params) { return axios({ method: "put", url, data: params }).then(response => { return checkStatus(response); }); }, delete(url, params) { return axios({ method: "delete", url, data: params }).then(response => { return checkStatus(response); }); } };
|
使用
首先在main.js
中进行引用
1 2 3
| import axios from './axios/axios'
Vue.prototype.$axios = axios;
|
然后在我们要使用的地方
1 2 3
| this.$axios.post('接口地址',{}).then(res=>{ })
|
将uni-request进行axios化封装
在flutter中优雅的封装网络请求