taro 實現 請求函數封裝


1.代碼如下:

src/utils/request.js

/**
 * 請求方法封裝
*/
import Taro from '@tarojs/taro'
import { API_USER, API_USER_LOGIN } from '@constants/api'

const CODE_SUCCESS = 200
const CODE_AUTH_EXPIRED = 401

function getStorage(key) {
  return Taro.getStorage({ key }).then(res => res.data).catch(() => '')
}

function updateStorage(data = {}) {
  return Promise.all([
    Taro.setStorage({ key: 'token', data: data['token'] || '' }),
    Taro.setStorage({ key: 'uid', data: data['uid'] || ''})
  ])
}

/**
 * 簡易封裝網絡請求
 * // NOTE 需要注意 RN 不支持 *StorageSync,此處用 async/await 解決
 * @param {*} options
 */
export default async function fetch(options) {
  const { url, payload, method = 'GET', showToast = true, autoLogin = true } = options
  const token = await getStorage('token')
  const header = token ? { 'Authorization': `Bearer ${token}` } : {}
  if (method === 'POST') {
    header['content-type'] = 'application/json;charset=utf-8'
  }

  return Taro.request({
    url,
    method,
    data: payload,
    header
  }).then(async (res) => {
    const { code, data } = res.data
    if (+code !== CODE_SUCCESS) {
      if (+code === CODE_AUTH_EXPIRED) {
        await updateStorage({})
      }
      return Promise.reject(res.data)
    }

    if (url === API_USER_LOGIN) {
      await updateStorage(data)
    }

    // XXX 用戶信息需展示 uid,但是 uid 是登錄接口就返回的,比較蛋疼,暫時糅合在 fetch 中解決
    if (url === API_USER) {
      const uid = await getStorage('uid')
      return { ...data, uid }
    }

    return data
  }).catch((err) => {
    const defaultMsg = +err.code === CODE_AUTH_EXPIRED ? '登錄失效' : '請求異常'
    if (showToast) {
      Taro.showToast({
        title: err && err.errorMsg || defaultMsg,
        icon: 'none'
      })
    }

    if (err.code === CODE_AUTH_EXPIRED && autoLogin) {
      Taro.navigateTo({
        url: '/pages/login/login'
      })
    }

    return Promise.reject({ message: defaultMsg, ...err })
  })
}

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM