Published on

封装小程序 wx.request 添加token

Authors
  • avatar
    Name
    Hansuku
    Twitter

先说一下为什么不使用fly.io,目前 fly.io 更大的方向还是为了多环境同步时做准备,一套代码适应 h5、native、weex 和小程序,这样看上去貌似确实使用它会方便很多,介于现在小程序和 mpvue 挖下的坑,想要在小程序上完美模拟浏览器时的 vue 并不好做,而且 fly.io 的小程序版本中的思路基本也是类似工厂模式,依靠 promise 来封装 wx.requeset,提供统一对外的拦截器,那么问题来了,我经手的项目中大量使用 token 来认证,而存储 token 的时候小程序和网页的接口是全然不同的,需要额外复杂的代码来同时适配多端的存储接口,对于我这个项目只有 3 周的开发周期而言肯定是不划算的...

那么先直接放封装部分的代码

//
//     The Code By DayiTech FrontEnd
//     Author:Han
//     Created At 2018/09/13 16:26:36
//
/**
 * 封装小程序wx.request,带自定义token,返回一个promise对象
 * @param {Object} url:接口
 * @param {Object} type:请求类型
 * @param {Object} data:参数,json类型
 * @param {function} success:成功的回调函数
 * @param {fcuntion} fail:失败的回调函数
 * @return {Primise}
 */
export default function (param) {
  let local_token = wx.getStorageSync('token')
  let header = {
    'content-type': 'application/json',
  }
  if (local_token) {
    header['Authorization'] = local_token
  }
  return new Promise((resolve, reject) => {
    wx.request({
      header: header,
      url: param.url,
      data: param.data,
      method: param.type,
      dataType: 'json',
      success: (res) => {
        if (res.header.Authorization) {
          this.$store.commit('REFRESHTOKEN', res.header.Authorization)
        }
        resolve(res)
      },
      fail: (res) => {
        reject(res)
      },
    })
  })
}

main.js注册

import Vue from 'vue'
import App from './App'
import request from './utils/request'
Vue.config.productionTip = false
Vue.prototype.$store = store

Vue.prototype.$request = request

const app = new Vue(App)
app.$mount()

export default {}

外部调用:

this.$request({
  url: 'your url',
  data: {},
  type: 'GET',
})
  .then((result) => {})
  .catch((err) => {})

token 部分还是使用 vuex 来管理和存储,这里使用 vuex 推荐分模块写法

src
action.js
getters.js
index.js
mutation - types.js
mutations.js

mutation-types.js

export const LOGINED = 'LOGINED'
export const REFRESHTOKEN = 'REFRESHTOKEN'
export const LOGOUT = 'LOGOUT'

mutations.js

import { LOGOUT, REFRESHTOKEN, LOGINED } from './mutation-types.js'

export default {
  [LOGINED](state, v) {
    state.token = v
    wx.setStorageSync('token', v)
  },
  [REFRESHTOKEN](state, v) {
    state.token = v
    wx.setStorageSync('token', v)
  },
  [LOGOUT](state, v) {
    state.token = ''
    wx.removeStorageSync({ token: 'token' })
  },
}

index.js

import Vue from 'vue'
import Vuex from 'vuex'

import mutations from './mutations'
import actions from './action'
import getters from './getters'

Vue.use(Vuex)

const state = {
  token: 0,
  userInfo: {},
}

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
})

然后在main.js引入和调用即可

import store from './store'

Vue.prototype.$store = store
*/}