封装axios
在封装之前首先我们要知道为什么要二次封装axios?
- api统一管理,不管接口有多少,所有的接口都可以非常清晰,容易维护
- 降低代码耦合度,避免组件内出现过多的重复代码。
- 请求拦截和响应拦截,如果不封装的话在组件内就会在每一个有请求的地方都要写重复的代码
首先封装网络模块的核心方法
import axios from "axios"
// import qs from 'qs'
import { Message, Loading } from 'element-ui'
/*
* 调用axios.create方法,配置一些属性,返回一个新的axios
*/
const instance = axios.create({
baseURL: "http://localhost:8080/",
timeout: 2000
})
/*
* 请求拦截
*/
let loading;
instance.interceptors.request.use(
config => {
// loading效果
loading = Loading.service({
fullscreen: true,
lock: true,
text: "正在加载,请稍等……",
spinner: "el-icon-loading"
})
return config
},
error => {
loading.close();
// 对错误请求的处理
// 弹出错误请求消息
Message({
showClose: true,
message: error.message,
type: "error"
})
return Promise.reject(error)
}
)
/*
* response拦截器 请求之后的操作
*/
instance.interceptors.response.use(
config => {
loading.close();
return config
},
error => {
return Promise.reject(error)
}
)
export default instance
在这里我并没有把请求方式封装进去,但是也是可以封装的
// 如果有这一步的封装的话,上面的导出就需要注释掉了
/* export default {
get(url, params) {
return new Promise(
(resolve, reject) => {
instance.get(url, params)
.then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
}
)
},
post(url, params) {
return new Promise(
(resolve, reject) => {
instance.post(url, params)
.then(response => {
resolve(response)
}).catch(error => {
reject(error)
})
}
)
}
} */
然后进一步封装并导出所有的请求方式,在使用的地方按需引入
export const GET = "get"
export const POST = "post"
export const POT = "pot"
export const DELETE = "delete"
封装api接口,然后导出,按需引入
const path = {
data:"data.json",
topSearch:"topSearch.json",
history:"history.json"
}
export default path
然后再定义一个管理所有请求的文件,导入封装的api接口以及请求方式,还有二次封装的axios请求
import fetch from "./modulesManager"
import path from "./api"
import {GET} from "./requestMethods"
export function getHomeList(params){
return fetch({
url:path.data,
method:GET,
params:params
})
}
export function getHotSearchList(params){
return fetch({
url:path.topSearch,
method:GET,
params:params
})
}
export function getSearchList(params){
return fetch({
url:path.history,
method:GET,
params:params
})
}
如果把请求方式也封装在网络模块的话就需要这样使用
/* export function getHomeList(url,params){
return fetch.get(url,params)
}
export function getHotSearchList(url,params){
return fetch.get(url,params)
}
export function getSearchList(url,params){
return fetch.get(url,params)
}
*/
这样一个简单的网络层就封装好了,这种东西每个公司都会有不同的写法,不过大体思路都是差不多的,就是可能使用的人越来越多然后模块封装的功能越来越多,但是最基本的功能还是一样的。