在做 vue 的项目中,获取后端数据使用 axios ,使用的地方可以说是很多了,我写代码总喜欢整整齐齐的,所以,对 axios 请求进行了封装,方便使用,减少了不少的冗余代码呢~
目录情况如下:
|-------src
| |-- api
| | |-- http.js
| | |-- roleApi.js
| |-- views
| | |-- role.vue
(1)首先,封装 axios 的 get、post方法、请求拦截(请求发出前处理请求)和响应拦截器(处理请求响应后的数据),新建文件 http.js:
import axios from 'axios'
import { Message } from 'element-ui'
// create an axios instance
const http = axios.create({
baseURL: '后端接口地址',
// baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 50000
// request timeout
})
// 设置 post、put 默认 Content-Type
http.defaults.headers.post['Content-Type'] = 'application/json'
http.defaults.headers.put['Content-Type'] = 'application/json'
// request interceptor 请求拦截(请求发出前处理请求)
http.interceptors.request.use(
config => {
// do something before request is sent
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor 响应拦截器(处理响应数据)
http.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
const res = response.data
const ressuc = res.success
// 后端返回成功失败是用 success 的true 和 false 判断,所以在这里就获取 response.data 的 success
if (ressuc) {
console.log('response', response)
return res
} else {
Message({
message: res.message || 'error',
type: 'error',
duration: 5 * 1000
})
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
// 封装get方法
export function get({ url, params }) {
return new Promise((resolve, reject) => {
http.get(url, {
params: params
}).then(res => {
resolve(res.data)
}).catch(err => {
reject(err.data)
})
})
}
// 封装post方法
export function post({ url, data }) {
return new Promise((resolve, reject) => {
http.post(url, data).then(res => {
resolve(res.data)
}).catch(err => {
reject(err.data)
})
})
}
(2)接下来,对不同的请求进行封装,新建文件 roleApi.js:
import { get, post } from './http' // 导入axios实例文件中方法
const server = {
//带参数的 get 方法
getById(param) {
return get({
url: '/role/getById',
method: 'get',
params: param
})
}
//不带参数的 get 方法
getAll() {
return get({
url: '/role/getAll',
method: 'get'
})
},
// post 方法
save(param) {
return post({
url: '/role/save',
method: 'post',
data: param
})
}
}
export default server
(3)最后,就是在业务模块直接导入 api 文件,role.vue 文件中使用:
import apis from '@/api/roleApi'
// 用try catch包裹,请求失败的时候就执行catch里的代码
try {
const param = {
id: 'admin'
}
const res = await apis.getById(param)
console.log('getById:', res)
} catch (e) {
//提示错误
console.log(e)
}
用这种方式,使用 axios 时只需要一句简单的代码既可以得到返回结果,可以说是很方便啦~