本文主要是介绍axios请求封装,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.request.js
/**axios封装
* 请求拦截、相应拦截、错误统一处理
*/
import axios from 'axios'
import QS from 'qs'
// import store from "../../store/index";
import router from '../../router/index'
import db from '../../common/storage'
import {
Message,
MessageBox
} from 'element-ui'
// 环境的切换
if (process.env.NODE_ENV == 'production') {
axios.defaults.baseURL = process.env.VUE_APP_API_URL1
} else {
axios.defaults.baseURL = ""
}
// axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
//
// 请求超时时间
axios.defaults.timeout = 100000
// 请求拦截器
axios.interceptors.request.use(
config => {
// 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
// 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断
const token = db.ss.get('token')
token && (config.headers.token = token)
// 设置url的前缀
config.url = process.env.VUE_APP_URL_PORT + config.url
if (config.url.indexOf("/sys/login") !== -1 && config.method == 'post') {
config.data = QS.stringify(config.data)
} else if (config.method == 'get') {
config.params = {
...config.params,
_t: Date.parse(new Date()) / 1000
}
}
return config
},
error => {
return Promise.error(error)
}
)
// 响应拦截器
let timer = false
let path = '/login'
axios.interceptors.response.use(
response => {
if (response.status === 200) {
if (response.data.code == 401) {
if (!timer) {
timer = setTimeout(() => {
MessageBox.alert('登录信息已过期,点击确认跳转至登录页', '提示', {
confirmButtonText: '确认',
callback: action => {
if (action === 'confirm') {
clearTimeout(timer)
timer = null
setTimeout(() => {
router.replace({
path: path,
query: {
redirect: router.currentRoute.fullPath
}
})
}, 1000)
}
}
})
}, 0)
}
} else {
return Promise.resolve(response)
}
} else {
return Promise.reject(response)
}
},
error => {
if (error.response && error.response.status) {
switch (error.response.status) {
case 401:
router.replace({
path: path
})
break
case 403:
// 清除token
db.ss.clear()
if (!timer) {
timer = setTimeout(() => {
MessageBox.alert('登录信息已过期,点击确认跳转至登录页', '提示', {
confirmButtonText: '确认',
callback: action => {
if (action === 'confirm') {
clearTimeout(timer)
timer = null
setTimeout(() => {
router.replace({
path: path,
query: {
redirect: router.currentRoute.fullPath
}
})
}, 1000)
}
}
})
}, 0)
}
break
// 404请求不存在
case 404:
Message({
message: '请求不存在',
type: 'error'
})
break
default:
Message({
message: error.response.data.message,
type: 'error'
})
}
return Promise.reject(error.response)
}
}
)
/**
* get方法,对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function get(url, params) {
return new Promise((resolve, reject) => {
axios
.get(url, {
params: params
})
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
}
/**
* get方法,下载文件对应get请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function getFile(url, params) {
return new Promise((resolve, reject) => {
axios({
method: 'get',
url,
params,
headers: {
'Content-Type': 'application/json; application/octet-stream'
},
responseType: 'blob',
timeout: 100000
}).then((res) => {
resolve(res)
}).catch(err => {
reject(err.data)
})
})
}
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function postFile(url, params, onUploadProgress) {
return new Promise((resolve, reject) => {
axios
.post(
url,
params, {
timeout: 100000,
onUploadProgress
})
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
}
/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/
export function put(url, params = {}) {
return new Promise((resolve, reject) => {
axios.put(url, params).then(
response => {
resolve(response.data)
},
err => {
reject(err)
}
)
})
}
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function post(url, params) {
return new Promise((resolve, reject) => {
axios
.post(url, params)
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
}
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function del(url, params) {
return new Promise((resolve, reject) => {
axios
.delete(url, {
params: params
})
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err.data)
})
})
}
2.使用
import {
get,
put,
post,
del
} from "../api/request";
//新增指标
export const addIndicatorInter = data => {
return post(
`${process.env.VUE_APP_URL_PORT_BASE}/indicator`,
data
);
};
// 获取指标列表
export const getIndicatorListInter = data => {
return get(
`${process.env.VUE_APP_URL_PORT_BASE}/indicator`,
data
);
};
这篇关于axios请求封装的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!