配置基地址以及拦截器
在/common/http.interceptor.js
文件中
const install = (Vue, vm) => {
// 此为自定义配置参数,具体参数见上方说明
Vue.prototype.$u.http.setConfig({
baseUrl: 'http://localhost:8080/api/service/member', // 跨域
// baseUrl: 'https://www.XXX', // 基地址
loadingText: '努力加载中~', // loding 加载中显示文字
loadingTime: 800, // 超过0.8秒显示加载中 loding效果
originalData:true, // 返回服务器的原始数据
});
// 请求拦截,配置Token等参数
Vue.prototype.$u.http.interceptor.request = (config) => {
// 引用token
// 方式一,存放在vuex的token,假设使用了uView封装的vuex方式
// 见:https://uviewui.com/components/globalVariable.html
// config.header.token = vm.token;
// Token 信息
config.header.Token = 'xxxxxx';
// 可以对某个url进行特别处理,此url参数为this.$u.get(url)中的url值
// if(config.url == '/user/login') config.header.noToken = true;
return config;
}
// 响应拦截,判断状态码是否通过
// Vue.prototype.$u.http.interceptor.response = (res) => {
// }
}
export default {
install
}
在main.js
中 注册
注意:注册要写在app实例挂载完成后
// 省略其他
const app = new Vue({
...App
})
// 导入拦截器
import httpInterceptor from '@/common/http.interceptor.js'
// 注册拦截器
Vue.use(httpInterceptor, app)
API集中管理
在/common/http.api.js
文件中
const install = (Vue, vm) => {
// 请求方式
const get = (params = {},url) => vm.$u.get(url, params);
const post = (params = {},url) => vm.$u.post(url, params);
// 具体请求
// 获取token
const getToken = (data)=> post(data,'/XXXX')
vm.$u.api = {getToken};
}
export default {
install
}
在在`main.js`中 注册 写在导入拦截器下
import httpApi from '@/common/http.api.js'
Vue.use(httpApi, app)
在`.vue文件`中使用
// promise 方法
click(){ // 点击事件执行
this.$u.api.getToken({mid:123})
.then(res=>{
console.log('resToken',res)
}).catch(err=>{
console.log('token',err)
})
}
// async await 方法
async click(){ // 点击事件执行
try{
const res = await this.$u.api.getToken({mid:123})
console.log('res',res)
}catch(err){
console.log('err',err)
}
}