## 集成`axios`
```shell
$ yarn add axios@next
```
## 封装`axios`
### 新建文件`/src/utils/request.js`,创建axios实例,配置请求拦截、响应拦截
```javascript
import axios from 'axios'
import {publicConfig} from '../utils/config'
import store from '../store'
import {ACCESS_TOKEN} from '../store/mutation-types'
import storage from 'store'
import {ElMessage, ElNotification} from 'element-plus'
// 创建axios实例
const service = axios.create({
// 服务端API地址
baseURL: publicConfig.BASE_API,
// 请求超时时间:25s,大文件需要更长
timeout: 25000
})
// 接口请求拦截
service.interceptors.request.use(config => {
// 让每个请求携带当前用户token
const token = storage.get(ACCESS_TOKEN)
if (token) {
config.headers['Access-Token'] = token
}
return config
})
// 接口响应拦截
service.interceptors.response.use((response) => {
const result = response.data
// status:正常200;服务器错误500;未登录401;没权限403
if (result.status === 500) {
ElMessage.error('服务器内部错误')
return Promise.reject(result)
}
if (result.status === 401) {
store.dispatch('Logout').then(() => {
ElNotification.error({
title: '温馨提示',
message: result.message,
duration: 2
})
// 刷新页面
setTimeout(() => {
window.location.reload()
}, 1200)
})
return Promise.reject(result)
}
// 200、403
return result
}, (error) => {
// 网络请求出错
const errMsg = ((error.response || {}).data || {}).message || '请求出现错误,请稍后再试'
ElNotification.error({
title: '网络请求出错',
message: errMsg,
duration: 2
})
return Promise.reject(error)
})
export {
service as axios
}
```