封装vue+axios请求方法(get、post、put、del)

以下内容根据自己需求配置即可

/**
 * http 请求模块
 */
import md5 from 'md5'
import axios from 'axios'
import { Toast } from 'vant'
import stringify from 'qs/lib/stringify'
import { camelizeKeys, decamelizeKeys } from 'humps'
import platform from './platform'
import store from '@/store'

const branch = process.env.NODE_BRANCH.toUpperCase()

let envAppKey = 'VUE_APP_KEY'
let envAppSecret = 'VUE_APP_SECRET'
if (process.env.NODE_ENV === 'production') {
  envAppKey += `_${branch}`
  envAppSecret += `_${branch}`
}
const appKey = process.env[envAppKey]
const appSecret = process.env[envAppSecret]

export async function request(url: string, options: Record = {}) {
  try {
    if (!(options.data instanceof FormData)) {
      options.data = decamelizeKeys(options.data || {})
    }
    const { method = 'GET', data: content } = options
    //这儿内容按自己公司实际需求配置即可
    const headers: Record = {
      'X-BDS-Phone-Model': '',
      'X-BDS-Phone-OS-Name': platform.os,
      'X-BDS-Phone-OS-Version': '',
      'X-BDS-APP-Platform': '3',
      'X-BDS-APP-Name': 'browser.hermes',
      'X-BDS-APP-Version': '2.3.5',
      'X-BDS-APP-Version-Code': '235',
      'X-BDS-City-ID': store.state.config.city.currentCityId || 1
    }
    if (window.isMiniProgram) {
      headers['X-BDS-APP-Name'] = 'miniprogram.hermes'
    } else if (platform.isWechat) {
      headers['X-BDS-APP-Name'] = 'web.hermes'
    }

    if (method !== 'GET') {
    /**
     * 来源渠道
     */
      const qrChannel = sessionStorage.qrChannel
      if (qrChannel) {
        content.qr_channel = qrChannel
      }
    }

    const contentLength = Object.keys(content).length > 0 ? JSON.stringify(content).replace(/[^\x00-\xff]/ig, '111').length : 0
    const sdate = new Date().toUTCString()
    const formatUrl = url.replace(/\?.+/, '')
    // 签名
    const signature = md5(
      `${md5(appSecret)}&${method}&${formatUrl}&${contentLength}&${sdate}`
    )
    /**
     * header 中添加自定义的字段
     * 由于ajax 不支持 设置Date 和 Content-Length
     * 用sdate 和 contentlength 然后nginx做转发的时候更改
     */
    Object.assign(headers, {
      sdate,
      contentlength: contentLength,
      Authorization: `${appKey}:${signature}`
    })
    const requestUrl = `${process.env.PREFIX}${url}`
    const res = await axios({
      url: requestUrl,
      ...options,
      headers,
      withCredentials: true,
      validateStatus: s => s < 500
    })
    const { status: httpStatus, data } = res
    if (httpStatus > 200 && httpStatus !== 401) {
      Toast(data.detail)
    }
    return {
      httpStatus,
      data: camelizeKeys(data) as Record
    }
  } catch (error) {
    Sentry.captureException(error)
    return {
      httpStatus: 500,
      data: {
        code: 0,
        detail: '网络异常, 请稍后重试'
      }
    }
  }
}

export async function get(url: string, options: Record = {}) {
  const { data = {}, ...otherOptions } = options
  let requestUrl = url

  /**
   * 来源渠道
   */
  const qrChannel = sessionStorage.qrChannel
  if (qrChannel) {
    data.qrChannel = qrChannel
  }

  if (Object.keys(data).length > 0) {
    requestUrl = `${url}?${stringify(decamelizeKeys(data))}`
  }
  const response = await request(requestUrl, otherOptions)
  return response
}

export async function post(url: string, options = {}) {
  const response = await request(url, { ...options, method: 'POST' })
  return response
}

export async function put(url: string, options = {}) {
  const response = await request(url, { ...options, method: 'PUT' })
  return response
}

export async function del(url: string, options = {}) {
  const response = await request(url, { ...options, method: 'DELETE' })
  return response
}

======
具体请求接口可以单独提取到一个文件夹,如:api.ts 文件内容如下

import { get, post, put } from '@/utils/http' //引入封装好文件。
export function getConfig() { //定义api 方法
  return get('/v1/config')
}
// 在组件里使用如下
import {getConfig} from 'api'
async getConfig(){
  const {httpStatus=200,data={}} = await getConfig()
}

你可能感兴趣的:(封装vue+axios请求方法(get、post、put、del))