1.创建api文件,在当前目录封装一个request.js文件,配置请求响应的拦截信息
/**
* @file axios请求封装
*/
import axios from 'axios'
import store from '../store/common'
import router from '../router/common'
import { Toast } from 'vant'
const Axios = axios.create({})
// 响应时间
Axios.defaults.timeout = 10000
// `withCredentails`选项表明了是否是跨域请求
Axios.defaults.withCredentials = true
// 设置默认请求头
Axios.defaults.headers = {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json; charset=UTF-8'
}
// 添加请求拦截器
Axios.interceptors.request.use(
config => {
// loadingInstance = Loading.service({
// fullscreen: true
// });
// 获取token
let token = store.getters.getToken
if (token) {
// 判断是否存在token,如果存在的话,则每个http header都加上token
config.headers.Authorization = token
}
return config
},
error => {
return Promise.reject(error)
}
)
// 添加返回拦截器
Axios.interceptors.response.use(
response => {
if (
typeof response != 'undefined' &&
(response.data.code == 1001 ||
response.data.code == 0 ||
response.data.code == 1000 ||
response.data.code == 1100 ||
response.data.code == 1200)
) {
return response.data
} else if (response.data.code == 20008) {
// 交班后选机器号
checkCode('当前无人当班,请选择机器号')
router.replace('/center/machine')
return response.data
} else if (response.data.code == 1006) {
// Token过期
checkCode('登录过期,请重新登录')
return response.data
} else if (typeof response != 'undefined' && response.data.msg) {
checkCode(response.data.msg)
return response.data
} else {
checkCode('操作失败,请重试')
}
return ''
},
error => {
if (error && error.response) {
switch (error.response.status) {
case 400:
error.message = '请求错误'
break
...
default:
}
} else {
error.message = '无法连接服务器'
}
// 对返回的错误处理
return Promise.reject(error)
}
)
// 请求失败错误信息提示
function checkCode(message) {
// 关闭loading
// loadingInstance.close();
// 弹出错误信息
Toast(message)
}
export default Axios
2.再建立一个index.js文件统一写请求接口,如下图:
3.全局暴露请求接口api,在vue.config.js文件中,配置chainwebpack,设置api的别名就可以全局使用api的接口了
chainWebpack: config => {
config.resolve.alias
.set('api', path.resolve('./src/api/index.js'))
config.plugin('provide').use(webpack.ProvidePlugin, [
{
api: 'api'
}
])
}
4.接口请求:直接可以使用await api.getName(index.js下对应的接口名字)
await api.pageSalesOrderProsDetailData(this.formDate).then(response => {
if (response.data) {
this.goodsList = this.goodsList.concat(response.data.content)
this.totalPages = response.data.totalPages
if (response.data.content.length < this.formDate.pageCount) {
this.$store.commit('SET_ALL_LOADING', true)
}
}
this.$store.commit('SET_SALES_RANK_MSG', this.goodsList)
})