Uni-app 封装uni.request请求

1、request.js文件

const API_URL = "/api/";

const REQ_HEADERS = {
  contentType: "Content-Type",
};
const CONTENT_TYPE = {
  json: "application/json;",
  form: "application/x-www-form-urlencoded;",
};
//请求loading
let ajaxTimes = 0;
const request = ({ url, method = "get", headers = {}, body = null } = {}) => {
  ajaxTimes++;
  uni.showLoading({
    title: "加载中",
    mask: true,
  });
  url = API_URL + url;
  url.indexOf("?") === -1 ? (url += "?") : (url += "&");
  url += "_t=" + new Date().getTime();
  //   post: [REQ_HEADERS.contentType]: CONTENT_TYPE.form,
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: method,
      data: body,
      header: Object.assign(headers, {
        Authorization: `Bearer ${uni.getStorageSync("token")}`,
        [REQ_HEADERS.contentType]: CONTENT_TYPE.form,
      }),
      success: (res) => {
        uni.hideLoading();
        if (res.data.code === -1004) {
          //根据code码判断是否需要重新登陆
          uni.removeStorageSync("token");
          uni.reLaunch({
            url: "/pages/login/index",
          });
          return;
        }
        if (res.statusCode === 403 || res.statusCode === 502) {
          uni.showToast({
            icon: "none",
            title: "系统错误!",
          });
          return;
        }
        if (res.data.code === 1) {
          resolve(res.data);
          return;
        }
        uni.showToast({
          icon: "none",
          title: res.data.msg,
        });
      },
      fail: (err) => {
        uni.showToast({
          icon: "none",
          title: "系统错误!",
        });
        reject(err);
      },
      //请求结束 成功失败都关闭loading
      complete: () => {
        ajaxTimes--;
        if (ajaxTimes === 0) {
          //  关闭正在等待的图标
          uni.hideLoading();
        }
      },
    });
  });
};
export default request;

 2、login-serice.js

import request from "@/utils/request";

// 验证码
export function loginCode(query) {
  return request({
    url: "code",
    method: "POST",
    body: query,
  });
}

3、页面使用login.vue 

<template>

</template>

<script>
	import { loginCode} from '../../common/api/login-serice.js'
	export default {
		name: 'login',
		data() {
			return {
                formData: {
                    username: '',
				    password: '',
                }
				
			}
		},
		methods: {
			//获取验证码
			async handleCodeImg() {
				let codeData = await loginCode()
			    ....
			},
		},
		onReady() {
		},
		mounted() {
			this.handleCodeImg()
		},

	}
</script>

<style lang="scss" scoped>

</style>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值