在实际项目中,所有的请求都有一些基本操作:
1:请求发过去的时候header里面携带token。
2:请求响应回来的时候拦截状态码或其他错误信息,做出相应的判断
axios是一个基于promise封装的一个http库,单纯的用用还是可以的,但是在实际项目中如果还是axios.get(…).then(…)这种写法就会给开发带来些麻烦,所以在进一步的封装axios是有必要的
一:构建一个axios对象实例
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
timeout: 60000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
if (store.getters.token) {
config.headers['sg-token'] = getToken()
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
// if the custom code is not 20000, it is judged as an error.
if (res.code !== 10000) {
Message({
message: res.msg || 'Error',
type: 'error',
duration: 5 * 1000
})
if (res.code === 100009) {
store.dispatch('user/logout').then(() => {
location.reload(true)
})
}
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// to re-login
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(new Error(res.msg || 'Error'))
} else {
return res
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
上面的代码主要描述了对axios的一个基本封装,首先创建了一个axios对象,设置了它的请求基本路径和请求响应时间。在请求发出去时拦截添加header头–token,在请求响应回来的时候对状态码进行判断,不同公司的状态码规定不一样,比如上面代码,code=10000,是请求成功的意思,code=100009,是登录失效,重新加载页面等
二:API的汇总与管理
import request from '@/utils/request'
export function login(data) {
return request({
desc: '登录',
url: '/warehouse/login',
method: 'post',
data
})
}
export function resetPassword(data) {
return request({
desc: '重置密码',
url: '/warehouse/login/reset/password',
method: 'post',
data
})
}
上面的代码引入了我们刚刚封装的那个axios对象的文件,将api的url,method,data传过去
三:main.js引入api文件&全局注册$http方法
import { api } from '@/api'
Vue.prototype.$http = api
四:具体页面使用
this.$http.resetPassword().then(res=>{})
好了,以上就是axios的一些基本封装问题,如果有别的需要还可以继续往上面加东西