下面是自用的axios封装(用到了lodash.isequal)
一、封装的代码
src下的axios文件夹
1.index.js
import https from './config'
import apiConfig from '../../public/apiConfig'
const main = {
/**
* @description: 项目接口地址
*/
basePath: apiConfig.BASEPATH,
/**
* @description: axios通用请求封装
* @param {string} options.path 接口地址
* @param {object} options.params 接口参数
* @param {object} options.config axios额外配置
* @return: axios promise实例
*/
Post (options) {
if (!options.path && typeof options.path !== 'string') {
console.error('请求地址无效!')
return false
}
return https.post(this.basePath + options.path, options.params, options.config)
},
Get (options) {
if (!options.path && typeof options.path !== 'string') {
console.error('请求地址无效!')
return false
}
return https.get(this.basePath + options.path, {
params: options.params
}, options.config)
}
}
export default main
2.config.js
import axios from 'axios'
import objIsEqual from 'lodash.isequal'
// 用来存储未完成的请求
const requests = []
/**
* @description: 判断请求是否存在
* @param {object} 请求数据
* @return: 存在的请求的下标
*/
const isExist = (req) => {
let res = -1
for (let index = 0; index < requests.length; index++) {
// console.log(req.params, requests[index].params)
if (objIsEqual(req.params, requests[index].params)) {
res = index
break
}
}
return res
}
/**
* @description: 移除已完成的请求
* @param {object} 请求数据
*/
const removeReq = (req) => {
const index = isExist(req)
if (index !== -1) {
requests.splice(index, 1)
}
// console.log(requests)
}
/**
* @description: 创建axios实列
*/
const instance = axios.create({
withCredentials: false, // 表示跨域请求时是否需要使用凭证
timeout: 20 * 1000
})
/**
* @description: 请求拦截器
*/
instance.interceptors.request.use(request => {
const req = {
params: {
data: request.data || '',
params: request.params || '',
method: request.method,
url: request.url
},
cancelToken: null
}
const reqIndex = isExist(req)
// console.log(reqIndex)
if (reqIndex !== -1 && requests[reqIndex].cancelToken) {
requests[reqIndex].cancelToken()
// 移除被取消的请求
requests.splice(reqIndex, 1)
}
if (!request.cancelToken) {
request.cancelToken = new axios.CancelToken(c => {
req.cancelToken = c
})
}
// 放入未完成请求数组
requests.push(req)
return request
}, error => {
return Promise.reject(error)
})
/**
* @description: 响应拦截器
*/
instance.interceptors.response.use(response => {
let data = ''
let params = ''
let res = {}
try {
data = response.config.data ? JSON.parse(response.config.data) : ''
params = response.config.params ? JSON.parse(response.config.params) : ''
} catch (error) {
data = response.config.data
params = response.config.params
}
const req = {
params: {
data: data,
params: params,
method: response.config.method,
url: response.config.url
}
}
removeReq(req)
// console.log(response)
switch (response.status) {
case 201:
res = response
break
default:
res = response.data
}
return res
}, error => {
if (error && error.response) {
let data = ''
let params = ''
const response = error.response
try {
data = response.config.data ? JSON.parse(response.config.data) : ''
params = response.config.params ? JSON.parse(response.config.params) : ''
} catch (error) {
data = response.config.data
params = response.config.params
}
const req = {
params: {
data: data,
params: params,
method: response.config.method,
url: response.config.url
}
}
removeReq(req)
switch (response.status) {
case 400:
error.message = '错误请求'
break
case 401:
error.message = '未授权,请重新登录'
break
case 403:
error.message = '拒绝访问'
break
case 404:
error.message = '请求错误,未找到该资源'
break
case 405:
error.message = '请求方法未允许'
break
case 408:
error.message = '请求超时'
break
case 500:
error.message = '服务器端出错'
break
case 501:
error.message = '网络未实现'
break
case 502:
error.message = '网络错误'
break
case 503:
error.message = '服务不可用'
break
case 504:
error.message = '网络超时'
break
case 505:
error.message = 'http版本不支持该请求'
break
default:
error.message = `连接错误${response.status}`
}
} else {
error.message = '连接到服务器失败'
}
// console.error(error)
return Promise.reject(error)
})
export default instance
3.public下的apiConfig.js
// const BASEPATH = 'http://192.1.2.246:8080/'
const BASEPATH = 'https://qt-hd.linker.cc/qtPay'
export default
{
BASEPATH
}
二、在页面中使用
1.入口文件main.js中
import axiosObj from '@/axios/index'
Vue.prototype.$https = axiosObj
2.post请求
this.$https
.Post({
path: '/srv/api/machineInfo',
params: {
sn: _this.$route.query.sn //请求参数
}
})
.then(res => {
if (res && res.code === 200) {
//操作请求的数据
}
})
3.get请求
get请求也差不多,具体用法看封装的代码
下面是简化版的
src下新建一个extend.js,里面放了一些拓展的常用方法
代码
import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
const basePath = document.getElementById('basePath').value
// const basePath = 'http://192.1.4.116:8080/hblhsrv/srv'
// const basePath = 'http://192.1.4.116:8080/newlhsrv/srv'
// 创建实例
var instance = axios.create({
baseURL: process.env.NODE_ENV === 'production' ? basePath : '/api',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'equipmentSource': 'WEB'
},
// withCredentials: true,
// crossDomain: true,
})
Vue.prototype.$get = function (url, cb) {
instance.get(url)
.then(function (res) {
cb && cb(res.data)
})
.catch(function (error) {
console.log(error)
})
}
Vue.prototype.$post = function (url, data, cb) {
data = qs.stringify(data)
instance.post(url, data)
.then(function (res) {
cb && cb(res.data)
})
.catch(function (error) {
console.log(error)
cb && cb(null)
})
}
用法
1.post
this.$post('/interactive/commentsReply', data, res => {
if (res.rt === 1) {
this.$q.notify({
message: '评论成功',
type: 'positive',
position: 'top'
})
this.$emit('handleComment')
this.hideComment()
} else {
this.$q.notify({
message: res.des,
type: 'negative',
position: 'top'
})
}
})
2.get
get也差不多