Vue项目中封装axios统一管理http请求

            <div id="content_views" class="markdown_views prism-tomorrow-night">
                <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
                    <path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>
                </svg>
                <h3><a name="t0"></a><a id="1_0"></a>1、需求说明</h3> 

在使用Vue.js框架开发前端项目时,会经常发送ajax请求服务端接口,在开发过程中,需要对axios进一步封装,方便在项目中的使用。

2、Vue项目结构

在本地创建Vue项目,目录结构如下:

 - public		静态资源文件
 - src
	|- assets		静态资源目录
	|- components	公共组件目录
	|- http			axios封装目录
	|- router		路由管理目录
	|- store		状态管理目录
	|- views		视图组件目录
	|- App.vue		根组件
	|- main.js		入口文件
 - package.json		npm配置文件
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在Vue项目中创建 http目录 作为axios的管理目录,在 http目录 下两个文件,分别是

  • /http/index.js 封装axios方法的文件
  • /http/api.js 统一管理接口的文件

3、代码示例

/http/api.js文件代码如下:

export default {
    'users_add': '/users/add',
    'users_find': '/users/find',
    'users_update': '/users/update',
    'users_delete': '/users/delete'
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

/http/index.js文件代码如下:

import axios from 'axios'
import api from './api'

//创建axios实例对象
let instance = axios.create({
baseURL: 'http://localhost:3000', //服务器地址
timeout: 5000 //默认超时时长
})

//请求拦截器
instance.interceptors.request.use(config=>{
//此处编写请求拦截的代码,一般用于弹出加载窗口
console.log('正在请求……')
return config
},err=>{
console.error('请求失败',err)
})

//响应拦截器
instance.interceptors.response.use(res=>{
//此处对响应数据做处理
console.log('请求成功!')
return res //该返回对象会传到请求方法的响应对象中
},err=>{
// 响应错误处理
console.log('响应失败!',err)
// return Promise.reject(err);
})

//封装axios请求方法,参数为配置对象
//option = {method,url,params} method为请求方法,url为请求接口,params为请求参数
async function http(option = {}) {
let result = null
if(option.method = 'get' || option.method = 'delete'){
//处理get、delete请求
await instance[option.method](
api[option.url],
{params: option.params}
).then(res=>{
result = res.data
}).catch(err=>{
result = err
})
}else if(option.method = 'post' || option.method = 'put'){
//处理post、put请求
await instance[option.method](
api[option.url],
option.params
).then(res=>{
result = res.data
}).catch(err=>{
result = err
})
}

<span class="token keyword">return</span> result

}

export default http

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

在main.js入口文件中引入封装好的 /http/index.js 文件,示例代码如下:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import http from './http'

Vue.config.productionTip = false
Vue.prototype.$http = http

Vue.use(Elementui)

new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

在App.vue根组件中测试axios请求,示例代码如下:

<template>
  <div>
    <button @click="getDate">发送请求</el-button>
  </div>
</template>

<script>
export default {
methods: {
getDate(){
this.$http({
method: 'get',
url: 'users_find'
}).then(res=>{
console.log(res)
})

<span class="token punctuation">}</span>

}
}
</script>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

这里需要有 http://localhost:3000/users/find 接口,不然请求会失败!

4、效果演示

启动Vue项目,在浏览器中访问Vue项目的地址,我的地址是 http://localhost:8080,点击按钮发送请求,获取的结果如下图所示。
在这里插入图片描述
到此,在Vue项目中就完成了简单的axios封装,你也可以根据自己的实际需求对axios进行封装,本文只是提供参考。

    </div>
posted @ 2024-03-11 09:41  mounter爱学习  阅读(76)  评论(0编辑  收藏  举报