axios封裝
import axios from './http';
import qs from 'qs';
const api = {
async get(url, data) {
let dataNew = data;
let time = (new Date()).valueOf();
if(dataNew) {
dataNew.time = time
}
try {
let res = await axios.get(url, {
params: dataNew
})
res = res.data
return new Promise((resolve, reject) => {
if (res.code === 200) {
resolve(res)
} else {
reject(res)
}
})
} catch (err) {
alert('服務(wù)器出錯(cuò)')
console.log(err)
}
},
async post(url, data) {
try {
let res = await axios.post(url, qs.stringify(data))
// let res = await axios.post(url, data)
res = res.data
return new Promise((resolve, reject) => {
if (res.code === 200) {
resolve(res)
} else {
reject(res)
}
})
} catch (err) {
alert('服務(wù)器出錯(cuò)')
console.log(err)
}
}
}
export { api }
簡(jiǎn)單設(shè)置本地mock數(shù)據(jù)
import axios from 'axios'
// axios 配置
axios.defaults.withCredentials = true //是否攜帶憑據(jù),比如:cookie
axios.defaults.timeout = 6000 //請(qǐng)求超時(shí)時(shí)間
let interceptorResponse = null
axios.interceptors.response.use((response) => {
interceptorResponse = response
if (isInterceptResponse('/dashboard/painter/recommend/list', false)) {
response.data =
{
'msg': 'success',
'data':
{
'recommend_list': [
{
'painter_id': '1',
'link_name': ['環(huán)節(jié)1', '環(huán)節(jié)2', '環(huán)節(jié)3'],
'style_name': ['風(fēng)格1', '風(fēng)格2', '風(fēng)格3'],
'recommend_url': 'http://image.japaholic.com/article/images/2017/01/1542.jpg',
'recommend_reason': '我是推薦理由'
},
{
'painter_id': '2',
'link_name': ['環(huán)節(jié)1', '環(huán)節(jié)2', '環(huán)節(jié)3'],
'style_name': ['風(fēng)格1', '風(fēng)格2', '風(fēng)格3'],
'recommend_url': 'http://image.japaholic.com/article/images/2017/01/1542.jpg',
'recommend_reason': '推薦理由'
},
{
'painter_id': '3',
'link_name': ['環(huán)節(jié)1', '環(huán)節(jié)2', '環(huán)節(jié)3'],
'style_name': ['風(fēng)格1', '風(fēng)格2', '風(fēng)格3'],
'recommend_url': 'http://image.japaholic.com/article/images/2017/01/1542.jpg',
'recommend_reason': '推薦理由'
},
{
'painter_id': '4',
'link_name': ['環(huán)節(jié)1', '環(huán)節(jié)2', '環(huán)節(jié)3'],
'style_name': ['風(fēng)格1', '風(fēng)格2', '風(fēng)格3'],
'recommend_url': 'http://image.japaholic.com/article/images/2017/01/1542.jpg',
'recommend_reason': '推薦理由'
},
]
},
'code': 200
}
}
function isInterceptResponse (url, isIntercept = true) {
if (!isIntercept) {
return false
}
// && interceptorResponse.status === 404
if (interceptorResponse.request.responseURL.indexOf(url) !== -1) {
return true
}
return false
}