封装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)
})
}
}
—————————————————————————
“在浮躁的夏季,听一首春天的歌,迎接远道而来的浪漫 ”