【小程序taro最佳實踐】http請求封裝(方便使用,增長token,統一錯誤日誌記錄和上報)

原創文章,做者:stark,如若轉載,請註明出處:https://shudong.wang/10231.html
圖片描述html

給你們提供思路,能夠借鑑哈,有什麼問題能夠留言
taro腳手架後面文章會慢慢講解更多技巧
https://github.com/wsdo/taro-...

爲何封裝

當咱們開發小程序的時候,常常會用到http請求,固然官方已經提供了請求的接口,可是咱們每次請求的時候,可能會加上token,每次請求都會加上,若是不封裝起來,會至關的麻煩,那麼又怎麼封裝呢?

特性

  • 暴露get方法
  • 暴露post方法
  • post自定義contentType
  • 增長配置文件
  • token定義
  • 添加判斷狀態,記錄異常信息
  • 增長異常錯誤logError日誌
  • 增長統一日誌上報

設計

須要對外暴露接口:get post
參數:url,傳輸的數據,請求頭
這樣咱們能夠很方便的使用了

在/service/下新創建一個api.jsgit

baseOptions 方法

baseOptions(params, method = 'GET') {
    let { url, data } = params
    let contentType = 'application/x-www-form-urlencoded'
    contentType = params.contentType || contentType
    const option = {
      isShowLoading: false,
      url: base + url,
      data: data,
      method: method,
      header: { 'content-type': contentType, 'token': token }, // 默認contentType ,預留token
      success(res) {

      },
      error(e) {
        logError('api', '請求接口出現問題', e)
      }
    }
    return Taro.request(option)
  },

get方法

get(url, data = '') {
    let option = { url, data }
    return this.baseOptions(option)
  },

post 方法

增長了contentType 不一樣的後端框架會要求不一樣的請求頭部
post: function (url, data, contentType) {
    let params = { url, data, contentType }
    return this.baseOptions(params, 'POST')
  }
這樣咱們就能夠很方便在action裏面使用了
import api from '../service/api'
api.get('news/list', params)

添加判斷狀態

2018-09-27-11-00-39

export const HTTP_STATUS = {
  SUCCESS: 200,
  CLIENT_ERROR: 400,
  AUTHENTICATE: 401,
  FORBIDDEN: 403,
  NOT_FOUND: 404,
  SERVER_ERROR: 500,
  BAD_GATEWAY: 502,
  SERVICE_UNAVAILABLE: 503,
  GATEWAY_TIMEOUT: 504
}

配置

export const base = "https://api.github.com/repos/"

增長異常錯誤logError日誌

export const logError = (name, action, info) => {
  if (!info) {
    info = 'empty'
  }
  try {
    let deviceInfo = wx.getSystemInfoSync() // 這替換成 taro的
    var device = JSON.stringify(deviceInfo)
  } catch (e) {
    console.error('not support getSystemInfoSync api', err.message)
  }
  let time = formatTime(new Date())
  console.error(time, name, action, info, device)
  // 若是使用了 第三方日誌自動上報
  // if (typeof action !== 'object') {
  // fundebug.notify(name, action, info)
  // }
  // fundebug.notifyError(info, { name, action, device, time })
  if (typeof info === 'object') {
    info = JSON.stringify(info)
  }

配合使用

import { HTTP_STATUS } from '../const/status'
import { base } from './config'
import { logError } from '../utils'

  baseOptions(params, method = 'GET') {
    let { url, data } = params
    // let token = getApp().globalData.token
    // if (!token) login()
    console.log('params', params)
    let contentType = 'application/x-www-form-urlencoded'
    contentType = params.contentType || contentType
    const option = {
      isShowLoading: false,
      loadingText: '正在加載',
      url: base + url,
      data: data,
      method: method,
      header: { 'content-type': contentType, 'token': token },
      success(res) {
        if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
          return logError('api', '請求資源不存在')
        } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
          return logError('api', '服務端出現了問題')
        } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
          return logError('api', '沒有權限訪問')
        } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
          return res.data
        }
      },
      error(e) {
        logError('api', '請求接口出現問題', e)
      }
    }
    return Taro.request(option)
  },

最終版本

import Taro from '@tarojs/taro'
import { HTTP_STATUS } from '../const/status'
import { base } from './config'
import { logError } from '../utils'

const token = ''

export default {
  baseOptions(params, method = 'GET') {
    let { url, data } = params
    // let token = getApp().globalData.token
    // if (!token) login()
    console.log('params', params)
    let contentType = 'application/x-www-form-urlencoded'
    contentType = params.contentType || contentType
    const option = {
      isShowLoading: false,
      loadingText: '正在加載',
      url: base + url,
      data: data,
      method: method,
      header: { 'content-type': contentType, 'token': token },
      success(res) {
        if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
          return logError('api', '請求資源不存在')
        } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
          return logError('api', '服務端出現了問題')
        } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
          return logError('api', '沒有權限訪問')
        } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
          return res.data
        }
      },
      error(e) {
        logError('api', '請求接口出現問題', e)
      }
    }
    return Taro.request(option)
  },
  get(url, data = '') {
    let option = { url, data }
    return this.baseOptions(option)
  },
  post: function (url, data, contentType) {
    let params = { url, data, contentType }
    return this.baseOptions(params, 'POST')
  }
}

所有代碼

若是能幫到你幫忙點個 star
https://github.com/wsdo/taro-...

項目目錄

2018-09-27-11-12-54

交個朋友

clipboard.png

相關文章
相關標籤/搜索