//1、https.js网络请求封装
'use strict'
import Vue from 'vue'
import router from '../router/index'
//import store from '../store/index'
import axios from 'axios'
//import qs from 'qs'
import {
setCookies,
getCookies,
removeCookies
} from './util'
import ElementUI from 'element-ui'
//生产 xxxx uat xxxx
let appid = 'xxx'
let vueobj = new Vue();
const toSignin = function (msg) {
removeCookies("token")
// var message = msg ? msg : "token过期,即将前往登录页面";
var message = "token过期,即将前往登录页面";
vueobj.$message.error({
showClose: true,
message: message,
duration: 3000,
onClose: function () {
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
});
}
});
}
/**
* 请求失败后的错误统一处理
* @param {Number} status 请求失败的状态码
*/
const errorHandle = (status, other) => {
// 状态码判断
switch (status) {
case 400:
vueobj.$message.error({
showClose: true,
message: "请求参数有误!",
duration: 3000
});
break;
case 403:
vueobj.$message.error({
showClose: true,
message: "没有操作权限!",
duration: 3000
});
break;
// 404请求不存在
case 404:
vueobj.$message.error({
showClose: true,
message: "请求不存在",
duration: 3000
});
break;
case 500:
vueobj.$message.error({
showClose: true,
message: "请求失败,服务器内部错误",
duration: 3000
});
break;
case 504:
vueobj.$message.error({
showClose: true,
message: "与服务器连接失败!",
duration: 3000
});
break;
default:
console.log(other);
}
}
//请求头中添加Authorization
axios.interceptors.request.use(config => {
// loading
return config
}, error => {
return Promise.reject(error)
})
// 响应拦截器
axios.interceptors.response.use(
response => {
// 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据
// 否则的话抛出错误
if (response.status === 200) {
if (response.data.success) {
return Promise.resolve(response.data);
} else {
return Promise.reject(response);
}
} else {
return Promise.reject(response);
}
},
// 服务器状态码不是2开头的的情况
// 这里可以跟你们的后台开发人员协商好统一的错误状态码
// 然后根据返回的状态码进行一些操作,例如登录过期提示,错误提示等等
// 下面列举几个常见的操作,其他需求可自行扩展
error => {
const {
response
} = error;
if (response) {
// 请求已发出,但是不在2xx的范围
errorHandle(response.status, response.data.message);
return Promise.reject(response);
} else {
// 处理断网的情况
// eg:请求超时或断网时,更新state的network状态
// network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
// 关于断网组件中的刷新重新获取数据,会在断网组件中说明
//store.commit('changeNetwork', false);
//toSignin();
//vueobj.$message.error({showClose: true, message: "与服务器连接失败!", duration: 3000});
var originalRequest = error.config;
if (error.code == 'ECONNABORTED' && error.message.indexOf('timeout') != -1 && !originalRequest._retry) {
// originalRequest._retry = true
// return axios.request(originalRequest);
vueobj.$message.error({
showClose: true,
message: "请求超时,请稍后重试!",
duration: 3000
});
return Promise.reject(response);
} else {}
}
}
);
//检查返回的自定义code值
function checkCode(res) {
if (res && res.status == 200) {
if (!res.data.success) {
switch (res.data.errorcode) {
case 'ANOMALY':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'NO_EXIST_API':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'IP_LIMIT':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'INTERNAL_SERVER_ERROR':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'API_LIMIT':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'NO_ACTION':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'NO_DATA':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'NO_APPID':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'NO_VERSION':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'NO_PERMISSION':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'NO_3DEX_4_TOKEN':
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
break;
case 'TOKEN_EXPIRED':
toSignin()
break;
default:
ElementUI.Message({
message: res.data.msg,
type: 'warning'
});
}
} else {
return res.data
}
}
}
export default {
post(data,action) {
return new Promise((resolve, reject) => {
axios({
method: 'post',
baseURL: '/gateway/interface', //'/gateway/interface'+ data.action, // 新网关/gateway/interface 老网关/appserver/interfaceHF.do
responseType: 'json',
data: {
"action": action,
"appid": appid, //生产 88ibnoktffyc88r4 uat wx7xqxokdsexnfrb
"token": getCookies("token"),
"req_time": data.req_time,
"version": data.version,
"data": data.data || {}
},
timeout: 15000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json; charset=utf-8' //网关时改成application/x-www-form-urlencoded; charset=UTF-8即可 application/json
}
}).then(
(res) => {
resolve(res)
}
).catch((err) => {
checkCode(res)
})
})
},
// 登录请求
postLog(data,action) {
return new Promise((resolve, reject) => {
axios({
method: 'post',
baseURL: 'xxxx', // 由于配置代理,只要接口地址不要域名
responseType: 'json',
data: {
"action": action,
"appid": appid,
"option": true,
"req_time": data.req_time,
"version": data.version,
"data": JSON.parse(data.data) || {}
},
timeout: 15000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json; charset=utf-8'
}
}).then(
(res) => {
checkCode(res)
resolve(res)
}
).catch((err) => {
checkCode(res)
})
})
},
// 登录验证码
postCode(data,action) {
return new Promise((resolve, reject) => {
axios({
method: 'post',
baseURL: '/gateway/interface',
responseType: 'json',
data: {
// "action": data.action,
"action": action,
"appid": appid,
"req_time": data.req_time,
"version": data.version,
"data": data.data || {}
},
timeout: 15000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json; charset=utf-8'
}
}).then(
(res) => {
checkCode(res)
resolve(res)
}
).catch((e) => {
checkCode(e)
})
})
},
get(params) {
return axios({
method: 'get',
baseURL: '/gateway/interface',
params, // get 请求时带的参数
timeout: 15000,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
}).then(
(response) => {
return checkStatus(response)
}
).then(
(res) => {
return checkCode(res)
}
)
},
}
//2、api接口管理样例
export default {
// 获取二维码
getQer(self, params) {
return self.http.postCode(params, 'appMarket.appMarket.captcha')
},
// 登录接口
login(self, params) {
return self.http.postLog(params, 'appMarket.appMarket.webLogin')
},
};
//3、将封装的请求跟api在引入到main.js中方便在全局中使用
Vue.prototype.http = http
Vue.prototype.$api = Api
//4、组件中使用demo
getCode() {
let self = this
self.$api.getQer(self, {
version: "V1.0",
req_time: new Date().getTime(),
data: {}
}).then(res => {
if (res.body.result) {
} else {
}
})
},
onLogin() {
let self = this
self.$api.login(self, {
version: "V1.0",
req_time: new Date().getTime(),
data: {}
}).then(res => {
if (res.body.result) {
} else {
}
})
},