vue axios的简易封装

本文介绍了一个简单的axios封装方法,用于规范前后端数据交互格式,统一处理错误数据,简化前端开发流程。封装包括创建axios实例,定义请求和响应拦截器,处理不同状态码,以及全局错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

axios封装

1:规范化前后端的数据格式,避免出现较大差距
2:前端统一格式,对错误的数据统一处理,便于前端开发

代码

	import Vue from 'vue'
	import axios from 'axios'
	import {bus} from './bus'
	// 创建aixos对象
	const instance = axios.create({
	    validateStatus: status => {
	        if (status > 400) {
	            console.warn(`HTTP 请求出错 status: ${status}`)
	        }
	        return status >= 200 && status <= 505
	    },
	    // `headers` are custom headers to be sent
	    headers: {'X-Requested-With': 'XMLHttpRequest'},
	    // csrftoken变量名
	    xsrfCookieName: 'data_csrftoken',
	    // cookie中的csrftoken信息名称
	    xsrfHeaderName: 'X-CSRFToken',
	    withCredentials: true
	})
	/**
	 * request interceptor
	 */
	instance.interceptors.request.use(config => {
	    // 绝对路径不走 mock
	    if (!/^(https|http)?:\/\//.test(config.url)) {
	        const prefix = config.url.indexOf('?') === -1 ? '?' : '&'
	        config.url += prefix + 'isAjax=1'
	    }
	    return config
	}, error => {
	    return Promise.reject(error)
	})
	// 数据处理提取方法体
	function getMsg (obj, key, message) {
	    if (Object.prototype.toString.call(obj) === '[object Array]') {
	        for (let val of obj) {
	            getMsg(val, key, message)
	        }
	    } else if (Object.prototype.toString.call(obj) === '[object Object]') {
	        for (let key in obj) {
	            let cur = obj[key]
	            getMsg(cur, key, message)
	        }
	    } else {
	        if (key !== '') {
	            obj = key + ': ' + obj
	        }
	        message.push(obj)
	    }
	}
	instance.interceptors.response.use(response => {
		// 规定data返回的数据类型为对象 对于不同的状态码可以做不同的处理 按照业务需求来
	    if (!response.data || typeof response.data === 'string') {
	        let msg = '接口请求异常,请联系管理员'
	        console.warn('接口异常,', 'HTTP状态码:', response.status)
	        if (!response.data) {
	            console.error(msg)
	        }
	        response.data = {
	            code: response.status,
	            msg: msg
	        }
	    } else if (response.status === 401) {
	        bus.$emit('show-login-modal')
	    } else if (response.status > 300) {
	        console.error('HTTP请求出错,状态码为:', response.status)
	        console.warn('请求信息:', response)
	        let msg = response.statusText
	        if (response.data && response.data.message) {
	            msg = response.data.message
	        }
	        response.data = {
	            code: response.status,
	            msg: msg
	        }
	    } else {
	        response.data.msg = ''
	    }
	    let messages = []
	    //  对于message做统一的数据处理,将message的数据组装成字符串
	    if (response.data.messages) {
	        if (Object.prototype.toString.call(response.data.messages) === '[object Object]') {
	            getMsg(response.data.messages, '', messages)
	            response.data.msg = messages.join('; ')
	        } else if (Object.prototype.toString.call(response.data.messages) === '[object Array]') {
	            response.data.msg = response.data.messages.join(';')
	        }
	    } else if (response.data.message) {
	        response.data.msg = response.data.message
	    }
	    if (response.data.code !== 'OK' && response.data.code !== 0) {
	    	// 对于特殊的业务code,也可以进行封装处理
	        if (response.data.code === 'data_SETTING_ERROR') {
	            bus.$emit('show-data-modal')
	        }
	        return Promise.reject(response)
	    }
	
	    return response
	}, error => {
	    return Promise.reject(error)
	})
	
	Vue.prototype.$http = instance
	
	export default instance

main.js里面引用ajax.js文件

	import ajax from './ajax'
	ajax.interceptors.response.use(response => {
	    return response
	}, error => {
	    // 登录控制
	    if (error.status === 401) {
	        // 可以在ajax文件里面做处理,也可以在当前地方调用,因为错误的状态码都走error的路线
	        window.location = window.login_url + '?c_url=' + window.location.href
	    }
	    // 权限控制
	    if (error.status === 403) {
	        bus.$emit('api-error:user-permission-denied')
	    }
	    return Promise.reject(error)
	})

总结

1:这个axios的封装比较简单,只对code,data,message进行统一的处理。
2:对于拦截请求,请求没有结束跳转路由,一个方法体多次请求,缓存这些问题也可以封装起来处理,这个后期进行添加
3:封装的axios能够有效地对后台数据做一次过滤,能够使前端联调数据更方便
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值