uniapp, vue3, ts, interface encapsulation, applet login

Create a public folder under src, and create request.ts in the public folder

//设置基地址
const baseUrl = 'https://meituan.thexxdd.cn/api'

//封装请求
function request(
  url: string,
  method: 'GET' | 'POST',
  data: string | object | ArrayBuffer
) {
  return new Promise((resolve, reject) => {
    //发起uni请求
    uni.request({
      url: baseUrl + url,//路径
      method,
      data,
      //进入接口成功
      success: (res) => {
        if (res.statusCode == 200) {
          resolve(res)
        } else if (res.statusCode == 401) {
          uni.showToast({
            title: "信息过期",
            icon: "none",
            duration: 1000
          })
          resolve(res)
        } else if (res.statusCode == 500) {
          uni.showToast({
            title: "服务器错误",
            icon: "none",
            duration: 1000
          })
          resolve(res)
        } else if (res.statusCode == 202) {
          uni.showToast({
            title: "服务器错误",
            icon: "none",
            duration: 1000
          })
          resolve(res)
        } else{
          uni.showToast({
            title: "服务器错误",
            icon: "none",
            duration: 1000
          })
          resolve(res)
        }
      },
      // 进入接口失败
      fail:(err)=>{
        uni.showToast({
          title:"服务器错误",
          icon:"none",
          duration:1000
        })
        reject(err)
      }
    })
  })
}
//抛出
export {request}

Create api.js in the public folder

// 引入封装好的接口
import {request} from "../request"


const RequestApi = {
// 第一个参数是去掉公共地址剩下的地址
// 第二个参数请求方式 支持多种方式  get post put delete 等等
// 第三个参数发送请求要配置的参数 无参数的情况下可以写成对象
  Frontpage: () => request('/frontpage', 'GET', {})
}
//抛出
export{RequestApi}

After the request is written, we still need to use the token for some logical operations, which need to be logged in the applet, and then write the method of logging in the applet

Write the request header in request.ts

1. Download js-base64 Download method: npm install -- save js-base64

2. Write the request header in the sealed request

3. Request the login interface of the applet. The blue word I wrote in ts is the standard interface type of ts. Just delete this with js

4. Add a click event to the login button on the login page, and the operation performed when the click event is triggered

Call the encapsulated login interface on the login page

5. Call the api interface to log in

6. Click Login

 7. When visiting some pages that need to be logged in, the background will return a failure message when there is no login or the login expires. The statusCode of this failure message is 401, so it needs to be judged when requesting the interface. If the return is 401, it needs to jump Go to the login page and log in again.

 

 code:

request.ts

const baseUrl = 'https://meituan.thexxdd.cn/api'

//获取token npm install -- save js-base64
import { Base64 } from 'js-base64'
function getToken(): string {
    const token = uni.getStorageSync('wxuser').user_Token || ''
    //后端和前端的约定 
    const base64_token = Base64.encode(token + ':')
    return 'Basic ' + base64_token
}

//请求
function request(url: string, method: 'GET' | 'POST', data: string | object | ArrayBuffer) {
    return new Promise((resolve, reject) => {
        uni.request({
            url: baseUrl + url,
            method,
            data,
            header: {
                Authorization: getToken()
            },
            success: (res: any) => {
                if (res.statusCode == 200) {
                    resolve(res)
                } else if (res.statusCode == 401) {
                    //权限过期
                    // 没有权限访问接口:跳转到登陆界面
                    uni.navigateTo({ url: '/pages/login-page/index' });
                    uni.showToast({
                        title: "信息过期",
                        icon: 'none',
                        duration: 1000
                    })
                    reject(res)
                } else if (res.statusCode == 400) {
                    uni.showToast({
                        title: '开发者某个字段或参数填写不对',
                        icon: 'none',
                        duration: 1000,
                    });
                    reject(res);
                } else if (res.statusCode == 500) {
                    uni.showToast({
                        title: "服务器错误",
                        icon: 'none',
                        duration: 1000
                    })
                    reject(res)
                } else if (res.statusCode == 202) {
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 1000
                    })
                    reject(res)
                } else {
                    uni.showToast({
                        title: "服务器错误",
                        icon: 'none',
                        duration: 1000
                    })
                    reject(res)
                }
            },
            fail: (err: any) => {
                uni.showToast({
                    title: "服务器错误",
                    icon: 'none',
                    duration: 1000
                })
                reject(err)
            }
        })
    })

}

log in page:

<template>
  <view class="Login-page">
    <image
      mode="aspectFill"
      src="https://diancan-1252107261.cos.accelerate.myqcloud.com/yiliao/denglu-yemian.jpg"
    ></image>
    <button @click="Login">授权登陆</button>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, toRefs } from "vue";
import { RequestApi } from "@/public/request";
// 授权登陆
function Login() {
  uni.getUserInfo({
    // desc: "获取个人信息",
    withCredentials: false,
    lang: "zh_CN",
    timeout: 10000,
    success: (res) => {
      let { avatarUrl, nickName } = res.userInfo;
      // 获取code
      uni.login({
        success: (code) => {
          console.log(code);

          uni.showLoading({ title: "登陆中", mask: true });
          ApiLogin(avatarUrl, nickName, code.code);
        },
        fail: (err) => {
          uni.showToast({ title: "登录失败", icon: "none", duration: 1000 });
        },
      });
    },
    fail: (err) => {
      uni.showToast({ title: "登录失败", icon: "none", duration: 1000 });
    },
  });
}

// 调用api接口登陆
async function ApiLogin(avatarUrl: string, nickName: string, code: string) {
  try {
    let obj = {
      appid: "",//id
      secret: "",//秘钥
      avatarUrl,
      nickName,
      code,
    };
    let res: any = await RequestApi.WxLogin(obj);
    // 存储用户信息到本地缓存,然后返回上一页
    uni.setStorageSync("wxuser", res.data.data);
    setTimeout(() => {
      uni.navigateBack({ delta: 1 });
      uni.hideLoading();
    }, 600);
  } catch (error) {
    uni.showToast({ title: "登录失败", icon: "none", duration: 1000 });
  }
}
</script>

Guess you like

Origin blog.csdn.net/dyx001007/article/details/127872201