Created
September 26, 2018 08:06
-
-
Save walijoy/1074647296c2dc46620909962e7077be to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios'; | |
import qs from 'qs'; | |
import store from '../store/index' | |
// axios 配置 | |
axios.defaults.timeout = 30000; | |
axios.defaults.baseURL = '/'; | |
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; | |
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'; //这是一个ajax请求 | |
// axios.defaults.headers['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content'); | |
//请求拦截器:传参序列化 | |
axios.interceptors.request.use((config) => { | |
if(config.method === 'post'){ | |
config.data = qs.stringify(config.data); | |
} | |
return config; | |
}, (error) => { | |
//todo 加错误显示 | |
//_.toast("错误的传参", 'warn', 1500, 'bottom'); | |
return Promise.reject(error); | |
}); | |
//响应拦截器,可做状态码判断就不用在本地判断了 | |
axios.interceptors.response.use((res) => { | |
//todo 可做返回结构统一验证 | |
if(res.code !== 200) { | |
// _.toast('错误', res.msg); | |
// return Promise.reject(res); | |
if(res.code === 401) { | |
store.commit('logout', this); | |
store.commit('clearOpenedSubmenu'); | |
} | |
} | |
return res; | |
}, (error) => { | |
// _.toast("网络异常", 'warn', 1500, 'middle'); | |
//todo 加错误显示 | |
return Promise.reject(error); | |
}); | |
/** | |
* 如果any是一个对象,则从尝试从对象中获取URI | |
* 对象中必须有url或uri或path属性,否则返回对象本身 | |
* @param any | |
* @returns {*} | |
*/ | |
export function getUrlFromAny (any) { | |
if(any instanceof Object) { | |
return any.hasOwnProperty('url') ? any['url'] : (any.hasOwnProperty('uri') ? any['uri'] : (any.hasOwnProperty('path') ? any['path'] : any)) | |
} | |
return any; | |
} | |
export function post (url, params) { | |
url = getUrlFromAny(url); | |
return new Promise((resolve, reject) => { | |
axios.post(url, params) | |
.then((response) => { | |
resolve(response.data); | |
}).catch((error) => { | |
reject(error); | |
}); | |
}); | |
} | |
export function get (url, params) { | |
//参数处理 | |
if(params && typeof params === 'object' && !params.hasOwnProperty('params')) { | |
params = {params: params} | |
} | |
//url处理,字符串不处理 | |
url = getUrlFromAny(url); | |
return new Promise((resolve, reject) => { | |
axios.get(url, params) | |
.then((response) => { | |
resolve(response.data); | |
}).catch((error) => { | |
reject(error); | |
}); | |
}); | |
} | |
//调用 | |
//http.post... | |
http.get('/api/test', {page:1}).then( | |
(res)=>{ | |
console.log(res.data) | |
}, | |
(err)=>{ | |
// | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment