创建axios实例
import axios from 'axios'// 创建axios实例对象,添加全局配置const service = axios.create({baseURL: config.baseApi,timeout: 8000})
请求拦截 --统一所有请求携带token
// 请求拦截service.interceptors.request.use((req) => {const headers = req.headers;const userInfo = storage.getItem('userInfo') || {}; //该处时引入的其他模块,方便获取 //token,可自行封装const { token = "" } = userInfoif (!token) headers.Authorization = 'Bearer ' + token; //如果token存在则设置请求头字段return req;})
响应拦截
// 响应拦截service.interceptors.response.use((res) => {//响应状态码为200时进入const { errorCode, data, errorMessage } = res.data;if (errorCode === 0) {return res.data;} else if (errorCode === 1000001) { //token失效处理 状态码不一定相同ElMessage.error(TOKEN_INVALID)setTimeout(() => {router.push('/login')storage.clearAll()}, 1500)return Promise.reject(TOKEN_INVALID)} else {ElMessage.error(errorMessage || NETWORK_ERROR)return Promise.reject(errorMessage || NETWORK_ERROR) //统一报错}},(err) => {//响应状态码!==200进入const {errorMessage} = err.response?.data || {}ElMessage.error(errorMessage || NETWORK_ERROR)return Promise.reject(errorMessage || NETWORK_ERROR)})
核心请求函数
function request(options) {options.method = options.method || 'get'if (options.method.toLowerCase() === 'get') {options.params = options.data;}let isMock = config.mock;if (typeof options.mock != 'undefined') {isMock = options.mock;}if (config.env === 'prod') {service.defaults.baseURL = config.baseApi} else {service.defaults.baseURL = isMock ? config.mockApi : config.baseApi}return service(options)}
为该实例的所有方法添加
['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {request[item] = (url, data, options) => {return request({url,data,method: item,...options})}})export default request; //最后暴露request
请求案例
function login(params) {return request({url: '/admin/auth/login',method: 'post',data: params})},
如果觉得《axios二次封装请求拦截和响应拦截》对你有帮助,请点赞、收藏,并留下你的观点哦!