uniapp封装request方法及调用
1.在common文件中新建request.js文件(没有common文件请新建,和pages平级)
//request.js export default { doRequest(url, method, data) { return new Promise((resolve, reject) => { var token = uni.getStorageSync('token') //获取本地存储的token,一般登录后存在本地 var apiUrl = global.reqHeard + url //见下APP.vue中 uni.request({ method: method, //POST GET之类 url: apiUrl, data: data, header: { 'Authorization': token //客户端请求标识,一般登录后存在本地 }, success: function(res) { console.log(res); // 根据后台返的状态(我司为code)判断拦截 if (res.code == 401) { // 拦截登录超时 uni.showToast({ icon: "none", title: '身份已过期,即将跳转到登录页' }) // 登录超时,关闭所有页面跳转登录 setTimeout(function() { uni.reLaunch({ url: 'pages/login' }) }, 1000); } else if (res.code != 0) { uni.showToast({ icon: "none", title: '请求错误' //有后台返的message就提示message }) return false } resolve(res) }, fail: function(err) { console.log('request请求失败') reject(err) }, }) }) }, }
2.APP.vue中的global
<script> global.reqHeard = 'http://192.168.0.1:8101'; //测试环境(仅为演示) // global.reqHeard = 'http://88.888.8:8101'; //生产环境(仅为演示) export default { onLaunch: function() { console.log('App Launch'); }, onShow: function() { console.log('App Show'); }, onHide: function() { console.log('App Hide'); }, methods: {} }; </script>
3.main.js中全局引用js
import Req from 'common/request.js'
Vue.prototype.$req = Req;
4.调用
<template>
<view></view>
</template>
<script>
export default {
data() {
return {};
},
onLoad() {},
methods: {
getInfo(e) {
var url = '/mobile/api/scanCode', //请求地址,仅为示例
data = { name: 'abc' }; //请求参数,仅为示例
this.$req
.doRequest(url, 'POST', data)
.then(res => {
console.log(res); //接口返回的内容
})
.catch(err => {
//请求失败
});
}
}
};
</script>
<style lang="scss"></style>

浙公网安备 33010602011771号