二次封装request请求

utils/showTips.js二次封装uni.showToast

export const $showMsg = (title='请求数据失败', duration=1500, icon) => {
  uni.showToast({
    title: title,
    duration: duration,
    icon: icon
  })
}

utils/storage.js二次封装StorageSync

/* 可以存储任意类型的值,可以存数组 */
const storage = {
  getItemSync (key) { /* 取的时候storage.getItem('键') */
    const value = uni.getStorageSync(key)
    const obj = value ? JSON.parse(value) : []
    if (obj.value) {
      return obj.value
    }
    return null
  },
  setItemSync (key, value) {
    const obj = {
      value
    }
    uni.setStorageSync(key, JSON.stringify(obj)) /* 存的时候'键', 数组名 */
  },
  removeItemSync (key) {
    uni.removeStorageSync(key)
  },
  clearSync () {
    uni.clearStorageSync()
  }
}
export default storage

局部使用storage


<script>
import storage from '@/utils/storage'
storage.getItemSync('键')
</script>

utils/request.js二次封装uni.request

import storage from './storage'
// 看文章最后  uniapp搭建的获取环境变量
import config from '@/common/config.js'
const BASE_URL = config.api()

export const request = (url, method, params) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url, // 地址
      method: method || 'get', // 请求方式
      header: { token: storage.getItemSync('user') ? storage.getItemSync('user').token : '' }, // token
      data: params || {}, // 参数
      success: (res) => {
        const data = res.data
        if(data.code === '401') {
          uni.navigateTo({ url: '/pages/login/login' })
          return
        } else if(data.code !== 200) {
          this.$showMsg('操作错误', '1500', 'error')
        }
        // 成功将data抛出
        resolve(data)
      },
      // ... 这里还可以做一些请求完成之后的提示,我就不做了
      fail: (err) => {
        this.$showMsg('系统错误', '1500', 'error')
        reject(err)
      }
    })
  })
}

全局挂载

import App from './App'

// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'

// 引入提示消息
import { showTips } from '@/utils/showTips'
Vue.prototype.$showMsg = showTips

// 引入request请求
import { request } from '@/utils/request'
Vue.prototype.$api = request

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
})
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif

如何使用

<template>
  <div>
    <button @click="fetchDate">点我请求数据</button>
  </div>
</template>

<script>
  // 用法
  import share from '@/minxins/store.js'
  export default {
    mixins: [share],
    data() {
      return {
      }
    },
    methods: {
      // 第一种写法:
      async fetchDate() {
        const res = await this.$api('/user','post', '世界')
        console.log(res);
      },
      // 第二种写法:
      function fetchDate() {
        this.$api('/user','post', '世界').then(res => {
          console.log(res);
        })
      }
    }
  }
</script>

 使用request-miniprogram插件的形式来完成uniapp请求

  1. 安装插件:npm install @escook/request-miniprogram
  2. 在main.js中导入下载好的request包

// #ifndef VUE3
import Vue from 'vue'
import App from './App'
// 引入包
import { $http } from '@escook/request-miniprogram';
import { $showMsg } from './utils/showTips.js';

// 引入vuex
import store from '@/store/index.js'

// 挂载包
uni.$http = $http

// 请求根路径
$http.baseUrl = 'https://www.uinav.com'

// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
  uni.showLoading({
    title: "数据加载中..."
  })
  // 判断当前请求是否为有权限的接口,因为只有登录之后才能用支付相关的接口
  if(options.url.indexOf('/token/') !== -1) {
    // 如果有权限的话就给options的header添加Authorization的字段,值为token
    options.header = {
      Authorization: store.state.m_user.token // 直接读取vuex中的token赋值给Authorization
    }
  }
} 

// 请求完成之后做一些事情
$http.afterRequest = function () {
  uni.hideLoading() // 返回数据之后隐藏动画
}
const app = new Vue({
    ...App,
		store
})

Vue.config.productionTip = false
Vue.prototype.$showMsg = $showMsg;

App.mpType = 'app'

app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
import App from './App.vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif

webpack构建的获取环境变量

// 环境配置
export default {
	api: function () {
		// 获取是什么环境
		let curVersion = process.env.NODE_ENV;
		console.log(curVersion);
		switch (curVersion) {
			case "production": //生产环境
				return "http://192.168.8.106:8083";
				// 开发环境
			default : return "http://192.168.8.106:8083"
		}
	}
}

 uniapp搭建的获取环境变量

export default {
	//接口请求域名配置
	api: function() {
		let curVersion = uni.getAccountInfoSync().miniProgram.envVersion;
		switch (curVersion) {
			case "develop": //开发版
				return "https://sharebk.oss-cn-hangzhou.aliyuncs.com";
			case 'trial': //体验版
				return "http://xxx.xxx.xxx.xxx:xxx"
			case 'release': //正式版
				return "http://xxx.xxx.xxx.xxx:xxx"
			default: //其他,默认调用正式版
				return "http://xxx.xxx.xxx.xxx:xxx"
		}
	}
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值