框架: uniapp +uview2.x
前言: 不会搭建项目的同学自己百度一下如何创建uniapp项目和引入uview
代码:
1.请求封装:
// 请求配置
import Config from "@/config/config.js"
module.exports = (vm) => {
uni.$u.http.setConfig((config) => {
config.baseURL = Config.websiteUrl;
config.timeout = 15000;
config.dataType = 'json',
config.header = {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Method": "POST,GET,UPLOAD,DELETE",
};
return config
})
uni.$u.http.interceptors.request.use((config) => {
// 是否加token
if (config?.custom?.auth) {
config.header.authorization = uni.getStorageSync('accessToken')
}
// 是否显示loading
if (config?.custom?.loading) {
uni.showLoading({
title: '加载中',
mask: true
})
}
return config
}, config => {
return Promise.reject(config)
})
uni.$u.http.interceptors.response.use((response) => {
if (response.config.custom.loading) {
uni.hideLoading()
}
switch (response.data.code) {
case 401 && uni.getStorageSync('accessToken'):
uni.$u.route({
type: 'reLaunch',
url: 'pages/public/login'
});
break;
case 200:
return response.data || response.rows
break;
case 500:
uni.$u.toast(response.data.msg)
return response.data
break;
default:
return response.data
break;
}
}, (response) => {
if (response.config.custom.loading) {
uni.hideLoading()
}
uni.$u.toast('请求失败,请稍后再试!')
uni.$emit('z-paging-error-emit')
return Promise.reject(response)
})
}
2:调用请求:
2.1: 引入接口地址(建议新建一个js文件专门存储接口地址 博主新建的文件 base.js )
2.1.1: auth–是否请求带token loading–是否请求显示loading
const http = uni.$u.http
export const login = (params,config = {custom: { auth: true,loading:true }}) => http.post('XXX接口地址XXXXXX', params, config)
2.2:调用请求(建议新建一个js文件专门存储接口方法 博主新建的文件 baseMixin.js)
2.2.1:建议所有的请求统一用Promise做同步处理 需要用同步的时候直接用即可
import {
login
} from '@/api/base.js';
export default {
methods: {
fnLogin(params) {
return new Promise((resolve, reject) => {
login({
//请求参数
registerSource: params.registerSource,
}).then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
})
},
}
}
3.页面使用:
<template>
<view class="login">
<view class="loginContent">
<view class="wrap">
<view class="content">
<button class="wxBtn checkeds" @tap="goLoginWx">
<text>手机号快捷登录</text>
</button>
</view>
</view>
</view>
</view>
</template>
<script>
import baseMixin from "@/mixin/baseMixin.js"
export default {
mixins: [baseMixin],
data() {
return {
};
},
methods: {
goLoginWx(){
this.fnLogin(params).then((res) => {
console.log('res', res);
})
}
}
}
</script>
完结撒花!不懂的自己多看两遍