封裝思想:php
封裝:vue
/** * Created by Administrator on 2017/7/20 0020. */import Vue from 'vue'import axios from 'axios'import qs from 'qs'axios.interceptors.request.use(config => { // loading return config}, error => { return Promise.reject(error)});axios.interceptors.response.use(response => { return response}, error => { return Promise.resolve(error.response)});function checkStatus (response) { // loading // 若是http狀態碼正常,則直接返回數據 if (response && (response.status === 200 || response.status === 304 || response.status === 400)) { return response; // 若是不須要除了data以外的數據,能夠直接 return response.data } // 異常狀態下,把錯誤信息返回去 return { status: -404, msg: '網絡異常' }}function checkCode (res) { // 若是code異常(這裏已經包括網絡錯誤,服務器錯誤,後端拋出的錯誤),能夠彈出一個錯誤提示,告訴用戶 if (res.status === -404) { // alert(res.msg) } if (res.data && (!res.data.success)) { // alert(res.data.error_msg) } return res}export default { install(Vue,options) { Vue.prototype.post=(url, data)=>{ return axios({ method: 'post', baseURL: 'http://aaa.xinphoto.me/index.php', url, data: qs.stringify(data), timeout: 10000, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }).then( (response) => { return checkStatus(response) } ).then( (res) => { return checkCode(res) } ) }; Vue.prototype.get=(url, params) =>{ return axios({ method: 'get', baseURL: 'http://aaa.xinphoto.me/index.php', url, params, // get 請求時帶的參數 timeout: 10000 }).then( (response) => { return checkStatus(response) } ).then( (res) => { return checkCode(res) } ) }; Vue.prototype.all=([callback1,callback2,callback])=>{ return axios.all([callback1,callback2,callback]).then(axios.spread(function(acct,perms,res){ return [acct,perms,res] })) } }, post(url, data){ return axios({ method: 'post', baseURL: 'http://aaa.xinphoto.me/index.php', url, data: qs.stringify(data), timeout: 10000, headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }).then( (response) => { return checkStatus(response) } ).then( (res) => { return checkCode(res) } ) }, get(url, params){ return axios({ method: 'get', baseURL: './static/image.json', url, params, // get 請求時帶的參數 timeout: 10000 }).then( (response) => { return checkStatus(response) } ).then( (res) => { return checkCode(res) } )}}