最近搭建template项目使用了axios用于接口请求,由于第一次自己搭建项目,遇到的坑比较多,原版也都是英文,于是自己翻译,baidu,终于搭建成功了axios的请求封装。话不多说,先上代码
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// 创建一个axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // 当跨域请求时发送cookie
timeout: 5000 // 请求超时
})
// 请求拦截器
service.interceptors.request.use(
config => {
// 在发送请求之前的处理
// if (store.getters.token) {
// //让每个请求携带token
// // ['X-Token']是一个自定义key
// //请根据实际情况进行修改
// config.headers['Content-Type'] = 'pplication/json;charset=UTF-8'
// }
// config.headers = {'content-type': 'application/x-www-form-urlencoded'}
return config
},
error => {
//处理请求错误
console.log(error) // for debug
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(res=>{
const code = res.data.code
if (code === 401) {
MessageBox.confirm(
'登录状态已过期,您可以继续留在该页面,或者重新登录',
'系统提示',
{
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.reload() // 为了重新实例化vue-router对象 避免bug
})
})
} else if (code !== 200) {
Notification.error({
title: res.data.msg
})
return Promise.reject('error')
} else {
return res.data
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
代码解析:
一、导入
1、axios:不用解释,必须
2、elementui的messagebox和message用于配置提醒和确认窗口
3、store:框架自带,引入后用于接口处理,store里面集成了vuex及项目默认引入的接口处理js
4、auth 里的getToken:用于给请求添加token。由于项目处于测试阶段,目前没有使用token校验。
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'//本人项目暂未使用token,可以先不引用
二、创建axios实例
创建实例用于配置请求的baseurl和请求超时时间设置
// 创建一个axios实例
const service = axios.create({
/** url = base url + request url,
*上一篇文章中在vue.config.js中已经配置了
*process.env.VUE_APP_BASE_API,
*这里可以直接为baserurl赋值
*/
baseURL: process.env.VUE_APP_BASE_API,
// withCredentials: true, // 当跨域请求时发送cookie,我没有用到,先注了
timeout: 5000 // 设置请求超时
})
三、设置请求拦截器
请求拦截器用于发送请求前的一些处理,主要使用场景比如设置请求头,为每一个请求配置token等,我的项目测试阶段不需要改变请求头也不需要传递token,相关代码注掉了,直接返回config。
// 请求拦截器
service.interceptors.request.use(
config => {
// 在发送请求之前的处理
// if (store.getters.token) {
// 请根据实际情况进行修改
// config.headers['X-Token'] = getToken()
// config.headers['Content-Type'] = 'pplication/json;charset=UTF-8'
// }
// config.headers = {'content-type': 'application/x-www-form-urlencoded'}
return config
},
error => {
//处理请求错误
console.log(error) // for debug
return Promise.reject(error)
}
)
四、设置响应拦截器
响应拦截器用于处理接口接收到的请求,统一拦截处理。这样引用接口时就不必为各种状态码重复写冗余代码。前后台状态码自行约定,这里只举个栗子
// 响应拦截器
service.interceptors.response.use(res=>{
const code = res.data.code
if (code === 401) {
MessageBox.confirm(
'登录状态已过期,您可以继续留在该页面,或者重新登录',
'系统提示',
{
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.reload() // 为了重新实例化vue-router对象 避免bug
})
})
} else if (code !== 200) {
Notification.error({
title: res.data.msg
})
return Promise.reject('error')
} else {
return res.data
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
最后导出service
export default service
大功告成!!