赞
踩
一、文件路径截图
2、新建一个文件app.js
- let host='http://172.16.192.40:8083/jeecg-boot/' //本地接口
- let myApi = {
- login: `${host}wx/wxUser/login`, //登录
- }
- module.exports = myApi
3、新建一个文件request.js
- import myApi from '@/utils/app.js';
- export const request = (options) => {
- console.log(options, `调用接口`)
- return new Promise((resolve, reject) => {
- const WXUSER = uni.getStorageSync('WXUSER');
- if (!options.url) return console.error('请传入URL')
- else sendRequest(options, resolve, reject);
-
- })
- };
- //封装的发送请求函数
- function sendRequest(options, resolve, reject) {
- const WXUSER = uni.getStorageSync('WXUSER');
- uni.request({
- url: options.url,
- data: options.data || '',
- method: options.method || 'POST',
- header: {
- "X-Access-Token": WXUSER.rememberToken, //传递的token
- },
- success: (res) => {
- if (res.data.code == 401) {
- console.log('返回401,token失效')
- wxlogin(options).then(() => {
- sendRequest(options, resolve, reject);
- });
- } else resolve(res.data)
- }
- })
- }
- //封装的登录 登陆成功后获取信息
- export async function wxlogin(options) {
- return new Promise((resolve, reject) => {
- uni.getUserInfo({
- success: (UserRes) => {
- uni.login({
- desc: 'weixin',
- success: res => {
- wx.request({
- url: myApi.login,
- method: 'POST',
- data: {
- weappCode: res.code,
- },
- success: res => {
- if (res.data.success) {
- console.log(res.data.result.wxUser)
- const WXUSER = res.data.result.wxUser
- const SYSUSER = res.data.result.sysUser
- uni.setStorageSync('WXUSER',WXUSER);
- uni.setStorageSync('SYSUSER',SYSUSER);
- resolve(); // 登录成功后,返回resolve
- } else {
- console.log('登录错误', res)
- reject(); // 登录失败时,返回reject
- }
- }
- });
- }
- });
- }
- })
- });
- }
4、页面使用
- <!-- 首页 -->
- <template>
-
- </template>
-
- <script>
- import myApi from '@/utils/app.js' //调用接口使用
- export default {
- components: {
-
- },
- data() {
- return {
- dataSource: [],
- };
- },
- onLoad() {
- this.loadData()
- },
-
- methods: {
- async loadData() {
- try {
- const res = await this.$request({
- url: myApi.CcrUgcList,
- method: 'GET',
- });
- console.log(res)
- if (res.code === 200) {
- this.dataSource = res.result.records
- }
- } catch (e) {
- // 失败执行
- console.log(`这个接口错误:${myApi.CcrUgcList}`)
- } finally {
- // 执行代码正确、报错都执行
- }
- },
-
- }
- };
- </script>
-
- <style lang="scss" scoped>
-
- </style>
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。