合理添加拦截器、明确API设计的好处:
- 统一管理接口
- 减少参数重传
- 规范前端开发
- 提升开发效率
合理设计拦截器
import axios from 'axios'
import Router from '@/router'
import { Notification } from 'element-ui'
// 获取全局baseURL
const baseUrl = window.g.baseURL
// 设置axios默认URL
axios.defaults.baseURL = baseUrl
// 对token添加过期处理
export default async (url, data) => {
const res = await axios.post(url, data)
// access_token过期
if (res.data.res === 1100) {
Notification.error({
title: '错误',
message: res.data.msg,
duration: 1500
})
Router.push('/')
}
return res
}
// 一、请求拦截器
axios.interceptors.request.use(function (config) {
// 拦截器处理(这里使用FormData传参,并简单添加token)
const fm = new FormData()
if (config.data) {
// 添加access_token
if (sessionStorage.access_token) {
fm.append('access_token',sessionStorage.access_token)
}
config.data = fm
return config
}, function (error) {
// 对请求错误做些什么
Notification.error({
title: '系统错误',
message: '服务器连接失败',
duration: 1500
})
return Promise.reject(error)
})
// 二、响应拦截器
axios.interceptors.response.use(function (response) {
return response
}, function (error) {
// 对响应错误做点什么
Notification.error({
title: '系统错误',
message: '服务器连接失败',
duration: 1500
})
return Promise.reject(error)
})
统一设计管理API
import axios from './axios'
const SUPERKET= 'superket'
// 登录
const ADMIN = '/admin'
export const adminLogin = (data) => axios(SUPERKET+ ADMIN + '/login', data)
// 管理员管理
export const adminList = (data) => axios(SUPERKET+ ADMIN + '/list', data)
export const adminAdd = (data) => axios(SUPERKET+ ADMIN + '/add', data)
export const adminEdit = (data) => axios(SUPERKET+ ADMIN + '/changePassword', data)
export const adminDel = (data) => axios(SUPERKET+ ADMIN + '/del', data)
// 系统设置
const SYSTEM = '/system'
export const systemList = (data) => axios(SUPERKET+ SYSTEM + '/list', data)
export const systemEdit = (data) => axios(SUPERKET+ SYSTEM + '/edit', data)
// 人员管理
const MEMBER = '/member'
export const memberList = (data) => axios(SUPERKET+ MEMBER + '/list', data)
export const memberAdd = (data) => axios(SUPERKET+ MEMBER + '/add', data)
export const memberEdit = (data) => axios(SUPERKET+ MEMBER + '/edit', data)
export const memberDel = (data) => axios(SUPERKET+ MEMBER + '/del', data)
网友评论