Vue 项目中封装 axios 请求

封装axios请求

首先,是在 vue-cli 脚手架上创建的项目基础上,在 src/http/index.js 中进行封装。
有关 vue-cli 创建项目的详细步骤,转战Vue-CLI创建项目

1、 在 src / http / index.js 中封装 axios 请求
// 导入axios
const axios = require('axios')

// 创建实例对象
const instance = axios.create({
    baseURL: 'http://localhost:3000' // 服务器地址
})

// 请求拦截器
instance.interceptors.request.use(config => {
	console.log('请求拦截', config)
	return config
}, err => {
	console.error('请求时异常', err)
	return
})

// 响应拦截
instance.interceptors.response.use(res => {
	// 此处可对响应回来的数据进行处理
	console.log('请求拦截', res)
	return res // 结果传回请求方法的响应对象中
}, err => {
	console.error('响应时异常', err)
	return
})

/**
 * 用于发送HTTP请求的方法
 * @param {*} option 发送请求的配置项
 * @returns 响应结果
 */
async function http({path, method, params}) {
	let result // 接受结果的变量
	
	if (method == 'get' || method == 'delete') { // get/delete 请求
		await instance[method](path, {
			params
		}).then(res => {
			result = res.data
		}).catch(err => {
			result = err	
		})
	} else if (method == 'post' || method == 'patch' || method == 'put') {
		// post/patch/put 请求
		await instance[method](path, params).then(res => {
			result = res.data	
		}).catch(err => {
			result = err	
		})
	}
	
	// 返回结果
	return result
}

// !!!切记,一定要抛出
export default http
2、在 mian.js 中引入 http 模块
import vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import http from './http'  // 引入 http 模块

// 挂载到vue 实例上
Vue.prototype.$http = http

new Vue({
	router,
	store,
	render: h => h(App)
}).$mount('#app')
3、在组件中使用 http 模块
export default {
	data () {
		return {
			stuList: []	
		}
	},
	created: {
		// 发送 http 请求
		this.$http({
			path: 'XXXX', // 服务器端的路由
			method: 'get', // 请求方式
			params: { // 请求参数
				xxx: xxxx
			}
		}).then(res => {
			// 请求成功的回调
			this.stuList = res.data	
		}).catch(err => {
			// 请求失败的回调
			console.log('请求失败...', err)
		})
	}
}

—————————————————————————
“在浮躁的夏季,听一首春天的歌,迎接远道而来的浪漫 ”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值