功能
- 支持RESful风格(get,post,delete,put,patch)
- 支持处理格式化URL(/demo/{id})
- 支持请求错误码跳转到指定url
使用
- 对外提供两个方法
http(url = '', data = {}, method = "GET")
:使用http请求
getUrl(url = '')
:构建完整的url
代码
import axios from 'axios';
const service = axios.create({
timeout: 30000
})
service.interceptors.request.use(config => {
return config;
}, error => {
Promise.reject(error);
})
service.interceptors.response.use(
response => {
let res = {};
res.status = response.status;
res.data = response.data;
return res;
},
error => {
if (error.response && error.response.status == 404) {
console.log("404错误")
}
return Promise.reject(error.response)
}
)
export function get(url, params = {}) {
params.t = new Date().getTime();
return service({
url: url,
method: 'get',
headers: {
},
params
})
}
export function post(url, data = {}) {
let sendObject = {
url: url,
method: "post",
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
data: data
};
sendObject.data = JSON.stringify(data);
return service(sendObject)
}
function put(url, data = {}) {
return service({
url: url,
method: 'put',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
data: JSON.stringify(data)
})
}
function deletes(url) {
return service({
url: url,
method: 'delete',
headers: {}
})
}
function patch(url) {
return service({
url: url,
method: 'patch',
headers: {}
})
}
function render(url, data) {
var re = /{([^]+)?}/
var match = ''
while ((match = re.exec(url))) {
url = url.replace(match[0], data[match[1]])
}
return url
}
const fetch = (options) => {
let url = process.env.VUE_APP_PATH + options.url;
url = render(url, options.data)
switch (options.method.toUpperCase()) {
case 'GET':
return get(url, options.data)
case 'POST':
return post(url, options.data)
case 'PUT':
return put(url, options.data)
case 'DELETE':
return deletes(url, options.data)
case 'PATCH':
return patch(url, options.data)
default:
return service(options)
}
}
export function http(url = '', data = {}, method = "GET") {
const options = { url: url, data: data, method: method }
return fetch(options).catch(error => {
console.log(error)
throw error
})
}
export function getUrl(url = '') {
return process.env.VUE_APP_PATH + url;
}