axios请求的相关代码放置于:src→api→index.js. indext.js基于axios的封装,便于处理统一处理POAT,GET等请求参数,请求头,以及错误提示信息等。具体可以参考:和服务端进行交互 | vue-element-admin。或者https://github.com/PanJiaChen/vue-element-admin/blob/master/src/utils/request.js
//小demo说明
import axios from 'axios' //导出一个axios的实例,并且这个实例要有请求拦截器,响应拦截器
const service = axios.create() //创建一个axios的实例
service.interceptors.request.use() // 请求拦截器
service.interceptors.response.use() // 响应拦截器
export default service //导出axios实例
下面我们看index.js文件中的写法实例
import axios from "axios";
import { Message, Loading, MessageBox } from "element-ui";
import { apiUrl, getConterntUrl } from "../utils/util";
import { contentUrls } from "@/utils/contentApi.js"
// const baseCon = require("base/config");
var baseUrl = "",
loading = Loading.service({
lock: true,
text: "加载中",
spinner: "el-icon-loading",
customClass: "loading-icon",
background: "rgba(0, 0, 0, 0.8)",
});
loading.close();
console.log('process.env.VUE_APP_CURENV', process.env.VUE_APP_CURENV);
switch (process.env.VUE_APP_CURENV) {
case "development":
baseUrl = ""
"https://cloudhospital.taikang.com"
break;
case "test":
baseUrl = "";
break
case "train": // 培训环境
//https://cloudhospital.taikang.com/cloudhospital-train/
baseUrl = "";
break
case "production":
baseUrl = "https://tkih.mobile.taikang.com"; //生产环境url
break;
case "hainan":
baseUrl = "https://ih.tkzhyl.com"; // 海南生产环境url
break;
}
// 请求接口基础路径
axios.defaults.baseURL = baseUrl; //测试域名
axios.defaults.timeout = 200000;//请求超时
index.js文件请求拦截器中
axios.interceptors.request.use(
(config) => {
if (config.url.indexOf('/tshomapp/pc/medical/getOrderChannelList') > -1 ||
config.url.indexOf('/tshomapp/pc/medical/getWorkGroupList') > -1) {
config.url = '/cloudhospital' + config.url; // 测试环境
console.log(55555, config.url);
} else if (contentUrls.includes(config.url) || contentUrls.includes(config.url.split('?')[0])) {
config.url = getConterntUrl + config.url; // 测试环境
console.log(44, config.url);
} else {
config.url = apiUrl + config.url; // 测试环境
}
return config;
},
(err) => {
loading.close();
Message({
message: "请检查您的网络连接并重试",
type: "warning",
duration: 2000,
customClass: "sucMsg",
center: true,
});
return Promise.reject(err);
}
})
index.js文件中响应拦截器
axios.interceptors.response.use(
(res) => {
loading.close();
if (res.status == 200) {
if (
res.data.code == "5002" ||
res.data.code == "BT5002" ||
res.data.code == "BT5033" ||
res.data.code == "BD2003"
) {
MessageBox.alert(res.data.msg, "提示", {
confirmButtonText: "去登录",
type: "warning",
}).then(() => {
sessionStorage.removeItem("token");
switch (process.env.VUE_APP_CURENV) {
case 'development':
window.location.href = "/";
break;
case 'test':
window.location.href = "/control-html/index.html#/";
break;
case 'train':
window.location.href = "/control-html-train/index.html#/";
break;
case 'production':
window.location.href = "/control-html/index.html#/";
break;
}
});
}
return res.data;
} else {
Message({
message: "请检查您的网络连接并重试",
type: "warning",
duration: 2000,
customClass: "sucMsg",
center: true,
});
}
},
(err) => {
loading.close();
Message({
message: "请检查您的网络连接并重试",
type: "warning",
duration: 2000,
customClass: "sucMsg",
center: true,
});
return Promise.reject(err);
}
);
最后index.js中export default axios;结尾
export default axios
下面就要关联API.js文件页面进行封装
import axios from "./index";
// import {getToken,getItem} from '@/utils/util'
export function api(url, method, request, other, header,responseType) {
let headers = Object.assign({
Authorization: "",
token: ""
},header);
if (sessionStorage.getItem("token")) {
// headers = {
// Authorization: "Bearer " + sessionStorage.getItem("token"),
// token: sessionStorage.getItem("token")
// };
headers.Authorization = "Bearer " + sessionStorage.getItem("token");
headers.token = sessionStorage.getItem("token");
} else {
delete headers.Authorization
delete headers.token
}
if(request && request.isShare){
// if(request && request.token){
headers.Authorization = "Bearer " + request.token;
headers.token = request.token;
}
console.log(5555,request);
if (method == "post") {
return axios({
url: url,
method: method,
params: other ? other : "",
data: request,
headers:headers,
responseType:responseType
}).then((res) => {
return res;
});
} else {
return axios({
url: url,
method: "get",
params: request,
headers:headers,
responseType:responseType
}).then((res) => {
return res;
});
}
}
xxx.vue文件中引用并调接口
<script>
import { api } from "@/api/API";
import axios from 'axios';
export default {
data(){
},
mounted(){
this.getConsultOf30DaysCode();
},
methods:{
//调接口的方法
getConsultOf30DaysCode(){
let params = {
"queryTime":this.reportDate,
"serviceOrgId":JSON.parse(sessionStorage.getItem('currentOrg')).serviceCd
}
let response = api("/tshomapp/pc/medical/getConsultOf30Days", "post", params);
response.then(res => {
if(res.code == 0){
this.getConsultOf30DaysList = res.data;
}
})
},
}
}
</script>