axios
一、安装axios
yarn add axios
or
npm install axios
二、 讲解
三、封装 (src/utils/request.js ) ( )
Notification (需要引入element-ui组件)
/**
* @file axios请求封装
* @version 1.0.0
*/
import Axios from 'axios'
// import Config from '@/settings'
import { getToken } from '@/utils/auth' // 获取token
const service = Axios.create({
baseURL: process.env.VUE_APP_API_URL, // url = base url + request url
timeout: 10000, // 响应超时时间
})
// const STRING_NETWORK_LOADING = '加载中...';
// const STRING_NETWORK_ERROR = '网络连接错误,请刷新或稍后重试!';
// 添加请求拦截器
service.interceptors.request.use(
(config) => {
if (getToken()) {
config.headers.common['Authorization'] = 'Bearer ' + getToken()
}
config.headers['Content-Type'] = 'application/json'
return config
},
(error) => {
return Promise.reject(error)
}
)
// 添加响应拦截器
service.interceptors.response.use(
// 服务器状态码:以2开头的的情况
(response) => {
if (response.status === 200) {
const res = response.data
return Promise.resolve(res)
} else {
return Promise.reject(new Error('Error'))
}
},
(error) => {
let code = 0
try {
code = error.response.data.status | error.response.data.code
} catch (e) {
if (error.toString().indexOf('Error: timeout') !== -1) {
Notification.error({
title: '网络请求超时',
duration: 5000,
})
return Promise.reject(error)
}
}
if (code) {
if (code === 50021) {
console.log('111')
// store.dispatch('LogOut').then(() => {
// // 用户登录界面提示
// Cookies.set('point', 401)
// location.reload()
// })
} else if (code === 403) {
// router.push({ path: '/401' })
} else {
const errorMsg = error.response.data.message
if (errorMsg !== undefined) {
Notification.error({
title: errorMsg,
duration: 5000,
})
}
}
} else {
Notification.error({
title: '接口请求失败',
duration: 5000,
})
}
return Promise.reject(error)
}
)
export default service