axios封装
文要封装了2种方式,第一种是很简洁的封装;第二种是带有请求拦截和响应的;适用于vue和react
首先使用npm安装一下axios: npm install axios --save-dev
根目录下新建封装的js文件
api.js存放的是请求地址,也不必单独新建,可以在request.js里面配置
建议直接挂载到全局js中,这样就不用一个个引入了
get请求用params传参;post用data
1、简洁的封装
这种方式很简单,只是用Promise简单的封装了直接调用即可,这种方式就不演示成功截图了
export default class HttpUtil {
//封装axios方法
static axiosHttp(options) {
try {
return new Promise((res, rej) => {
axios(options)
.then(val => {
res(val)
}).catch(error => {
console.log(error)
})
})
} catch (error) {
console.log("请求失败,请刷新网页!!");
}
}
}
使用
在对应的vue文件中引入
import ApiUtil from "@utils/api"
import HttpUtil from "@utils/request"
HttpUtil.axiosHttp({
url: `${ApiUtil.domin}/adminBanner/list`,
method: 'get',
params: {
paramsA: xxx,
paramsB: xxx
}
}).then((res) => {
console.log(res.data)
}).catch((err) => {
console.log(err)
})
2、带有拦截器的封装
由于后台暂时没返回token,这里的token就暂用的userId,可以存到缓存中,也可以放到vuex中
const axios = require("axios")
const { localGetStorage } = require('./base')
const instance = axios.create();
const cancleMap = new Map()
console.log(localGetStorage)
//设置code码状态
const codeMessage = {
400: '请求错误',
401: '登录状态失效,请重新登录',
403: '拒绝访问',
404: '请求地址不存在',
500: '服务器繁忙',
502: '网关错误',
503: '服务不可用,服务器暂时过载或维护',
504: '网关超时'
}
// 携带 cookie,目前没啥用,因为是 token 鉴权
axios.defaults.withCredentials = true
//设置请求超时
axios.defaults.timeout = 6000
// headers 信息
axios.defaults.headers['token'] = localGetStorage('accessToken') || ''
instance.interceptors.request.use((config) => {
if (cancleMap.has(`${config.url}-${config.method}`)) {
let cancle = cancleMap.get(`${config.url}-${config.method}`)
cancle.cancel('重复提交');
cancleMap.delete(`${config.url}-${config.method}`)
}
let source = axios.CancelToken.source();
config.cancelToken = source.token;
cancleMap.set(`${config.url}-${config.method}`, source)
return config
}, error => {
return Promise.reject(error);
})
instance.interceptors.response.use(res => {
if (typeof res.data !== 'object') {
alert('服务端异常,请稍后重试!!!')
return Promise.reject(res)
}
if (res.status !== 200) {
alert(codeMessage[res.status])
return Promise.reject(res.data)
}
// console.log(codeMessage[res.status])
console.log("response:", res)
return res
})
module.exports = instance
使用:
import httpRequest from '../utils/request'
httpRequest({
url: `${url}/products/list`,
method: 'post'
}).then(res => {
console.log(res)
})
下面我们找个接口请求一下看看效果
3、其他功能封装
获取浏览器及操作系统(getDeviceOS.js)
这里的代码还能简化一点,不用那么多if else。我就懒得改了
//获取浏览器及其版本
export function getExploreType() {
const system = {}
const userAgent = navigator.userAgent.toLowerCase()
let res = null
if (res = userAgent.match(/rv:([\d.]+)\) like gecko/)) {
system.explore = 'IE'
} else if (res = userAgent.match(/msie ([\d\.]+)/)) {
system.explore = 'IE'
} else if (res = userAgent.match(/edge\/([\d\.]+)/)) {
system.explore = 'Edge'
} else if (res = userAgent.match(/firefox\/([\d\.]+)/)) {
system.explore = 'Firefox'
} else if (res = userAgent.match(/(?:opera|opr).([\d\.]+)/)) {
system.explore = 'Opera'
} else if (res = userAgent.match(/chrome\/([\d\.]+)/)) {
system.explore = 'Chrome'
} else if (res = userAgent.match(/version\/([\d\.]+).*safari/)) {
system.explore = 'Safari'
} else {
system.explore = '位置的浏览器'
system.version = '位置的浏览器的位置版本'
}
if (res) {
system.version = res[1]
}
return system
}
// 获取操作系统
export function getOS() {
const userAgent = navigator.userAgent || ''
const appVersion = navigator.appVersion || ''
if (/Windows Phone/i.test(appVersion)) {
return 'WindowsPhone'
}
if (/iphone/i.test(userAgent) || /ipad/i.test(userAgent) || /ipod/i.test(userAgent)) {
return 'ios'
}
if (/android/i.test(userAgent)) {
return 'android'
}
if (/mac/i.test(appVersion)) {
return 'MacOSX'
}
if (/win/i.test(appVersion)) {
return 'Windows'
}
if (/linux/i.test(appVersion)) {
return 'Linux'
}
return '未知的操作系统'
}
缓存相关封装
export function localGetStorage(key) {
const value = window.localStorage.getItem(key)
try {
return JSON.parse(window.localStorage.getItem(key))
} catch (error) {
console.log('error:',error)
return value
}
}
export function localSetStorage(key, value) {
window.localStorage.setItem(key, JSON.stringify(value))
}
export function localRemoveStorage(key) {
window.localStorage.removeItem(key)
}