安装
npm install --save axios
在 main.js中引入
inport axios "axios"
在http文件夹中新建api.js文件
引入axios
inport axios "axios"
post、get请求进行封装

get 请求:

 export function get(url,api,params){
 	return	axios({
		method:'get',
		url:api,
		baseURL:url,
		params:params
	}).then(response => response.data).catch((err)=>{
		console.log(err)
	})
 }

postJson请求:

export function postJson(url.api,data){
	return axios({
		method:'post',
		url:api,
		baseURL:url,
		headers:{'Content-Type':'aplication/json'},
		data:data
	}).then(response => response.data).catch((err) => {
		console.log(err)
	})
}

postForm请求:

export  function posrForm(url,api ,data){
	return axios({
		method:'post',
		url:api,
		baseURL:url,
		headers:{'Content-Type':'application/x-www-form-urlencoded'},
		data:data,
		transformRequest:[function (data){
			let ret = '',
			for(let it in data){
				ret += encodeURIComponent(it) + "=" 6 encodeURIComponent(data[it]) + '&'
			}	
			return ret
		}]
	}).then(response => response.data).catch((err) => {
		console.log(err)
	})
}

封装完成了之后对他们进行输出(install方法将被作为Vue的参数调用)

export default{
	install(Vue){
		Vue.prototype.getAxios = (url,api,params) => get(url,api,params),
		Vue.prototype.pJson = (url,api,params) => postJson(url,api,params),
		Vue.prototype.pForm = (url,api,params) => postForm(url,api,params)
	}
}

在main.js中引入并且注册
import axiosApi from "@/http/api.js"
Vue.use(axiosApi)
axios有两个拦截器请求拦截器,响应拦截器可以进行处理
响应拦截器:

axios.intercepors.response.use(response => {
	if(response.data.code === 401){
		router.replace({
			path:'/login',
			query:{redirect: router.currentRoute.fullPath}
		})
	}
	return response
}, err => {
		if(err && err.response){
			switch(err.response.status){
				case 400:
					console.log("错误请求")
				break
				case 401:
					this.$store.commit('delToken')
					console.log("未授权,请重新登录")
				break
				case 403:
					console.log("拒绝访问")
				break
				case 404:
					console.log("请求错误,未找到该资源")
				break
				case 404:
					console.log("请求方法为允许")
				break
				case 408:
					console.log("请求超时")
				break
				case 500:
					console.log("服务器端出错")
				break
				case 501:
					console.log("网络未实现")
				break
				case 502:
					console.log("网络错误")
				break
				case 503:
					console.log("服务不可用")
				break
				case 504:
					console.log("网络超时")
				break
				case 505:
					console.log("http版本不支持该请求")
				break
				default:
					console.log(`连接错误${err.response.status}`)
			}
		}else{
			console.log('连接到服务器失败')
		}
})

请求拦截器:

axios.interceptors.request.use(config => {
	if(store.state.info.token){
		config.headers.common['token'] = store.state.info.token
	}
	return config
}, err => {
	return Promise.reject(err)
})
Logo

前往低代码交流专区

更多推荐