service.js 页面
javascript">import axios from 'axios'
// 创建axios实例
const instance = axios.create({baseURL: 'http://gcm-test.jhzhkj.cn:8600/h5card/',timeout: 5000, // 请求超时时间headers: {get: {'Content-Type': 'application/x-www-form-urlencoded'},post: {'Content-Type': 'application/json',}}
});// 请求拦截器
instance.interceptors.request.use(config => {// 可以在这里添加请求头等信息// config.headers['accesstoken'] = localStorage.getItem('accesstoken');const token = localStorage.getItem('accesstoken');const userId = 'clientId_pj9A9xEt8Y2YaEyQ9eEx';if (token) {config.headers.accesstoken = `${token}`;config.headers.userId = `${userId}`;}return config;},error => {// 请求错误处理console.log('请求错误处理',error); // for debugreturn Promise.reject(error);}
);// 响应拦截器
instance.interceptors.response.use(response => {// if ( response.msg == '登录已失效,请退出重新登录!') {// console.log('失败失败',response)// }const res = response.data;// 如果返回的状态码为200,说明成功,可以直接返回数据if (res.code === 200) {return res;} else {console.log(res,'响应拦截器 接口返回的错误数据')if(res.code == 500){alert('请稍后再试')}// 其他状态码都当作错误处理// 可以在这里对不同的错误码进行不同处理return Promise.reject({message: res.msg || 'Error',status: res.code});}},async error => {// originalRequest._retry 在axios中表示一个布尔值,用于控制请求的重试机制。当_retry设置为true时,表示当前请求将被重试。const originalRequest = error.config;// token过期 重新刷新Tokenif (error.response.data.code === 401 && !originalRequest._retry) {originalRequest._retry = true;try{let paramsData = {clientId: "c2YaEyEx", //IDclientSecret: "bb92aN9w", //秘钥};const res = await instance.post('/client/getToken', paramsData);const accesstoken = res.data.accesstoken;localStorage.setItem('accesstoken', accesstoken);instance.defaults.headers.common['accesstoken'] = `${accesstoken}`;return instance(originalRequest);}catch(refreshError){return Promise.reject(refreshError);}}// 对响应错误做处理// console.log('对响应错误做处理err' + error); // for debugreturn Promise.reject(error);}
);export const httpPost = (url, data = {}) => {return new Promise((resolve, reject) => {instance({url,data,method: 'post'}).then((response) => {if (response && response.code === 200) {resolve(response)} else {alert(response.msg)reject(response && response.msg)}})})
}export const httpGet = (url, params = {}) => {return new Promise((resolve, reject) => {instance({url,params,method: 'get'}).then((response) => {if (response && response.code === 200) {resolve(response.data)} else {alert(response.msg)reject(response && response.msg)}})})
}
api/common.js页面
javascript">import { httpPost,httpGet } from '@/utils/service';
// 获取token
export function getToken(params) {return httpPost('/client/getToken',params);
}
vue文件里应用
javascript">import { getToken } from "@/api/common";const getHome = () => {let paramsData = {clientId: "8Y9eEx", };getToken(paramsData).then((res) => {if (res.code == 200) {if (res && res.data.accesstoken) {localStorage.setItem("accesstoken", res.data.accesstoken);}}});
};