人生须知负责任的苦处,才能知道尽责任的乐趣。——梁启超
今天把老项目uniapp
的http
封装代码cv
过来,发现用不了了,原因是uView
版本升级了没适配
原先uView 1.x
的方式:
Vue.prototype.$u.http.setConfig({
baseUrl: 'http://localhost:8080/ruben',
loadingText: '加载中...',
loadingTime: 100,
});
Vue.prototype.$u.http.interceptor.request = (config) => {
const token = uni.getStorageSync('token');
config.header.token = token;
return config;
}
Vue.prototype.$u.http.interceptor.response = (res) => {
if (res.code == 0) {
return res;
} else if (res.code == 401) {
vm.$u.toast('验证失败,请重新登录');
uni.removeStorageSync("token")
vm.$u.route('/pages/login/login')
return false;
} else {
return res;
}
}
现在uView 2.x
的方式:
Vue.prototype.$u.http.setConfig((config) => {
return {
...config,
baseUrl: 'http://localhost:8080/ruben',
loadingText: '加载中...',
loadingTime: 100,
}
});
Vue.prototype.$u.http.interceptors.request.use((config) => {
const token = uni.getStorageSync('token');
config.header.token = token;
return config;
})
Vue.prototype.$u.http.interceptors.response.use((res) => {
if (res.code == 0) {
return res;
} else if (res.code == 401) {
vm.$u.toast('验证失败,请重新登录');
uni.removeStorageSync("token")
vm.$u.route('/pages/login/login')
return false;
} else {
return res;
}
})