欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于axios封装fetch方法及调用实例

程序员文章站 2022-08-27 23:54:48
基础axios用法请看axios官网 //依赖于axios对私有ajax进行修改 import qs from 'qs' import axios from...

基础axios用法请看axios官网

//依赖于axios对私有ajax进行修改
import qs from 'qs'
import axios from 'axios'
import router from 'router/index'
import {errorprompt, loading, closeloading} from 'util/util'
export const status = {
 success: '100',
 net_err: '101', // 网络连接异常,请稍候再试
 biz_err: '103', // 业务请求异常
 no_auth: '104'
}
export function fetch(options) {
 return new promise((resolve, reject) => {
 let instance = axios.create({
  baseurl: process.env.base_api,
  timeout: 2000,
  headers: {
  // "tracecode": window.encodeuricomponent(json.stringify({"ua":"","cv":"20161230","token":"3dwo0onuuspkvjcp8tk","os":"windows10","app":"kind","ws":"1*1","pkey":"f8caf7d7-a5d4-4710-b06f-28a922b6a467"}))
  "tracecode": commonbizheader(ismanager(options)),
  'content-type': 'application/x-www-form-urlencoded'
  },
  transformrequest: [function (data) {
  // do whatever you want to transform the data
  let ret = ''
  for (let it in data) {
   ret += encodeuricomponent(it) + '=' + encodeuricomponent(data[it]) + '&'
  }
  return ret
  }]
 });
 instance.interceptors.request.use(function (response) {
  // 请求拦截
  loading();
  return response;
 }, function (error) {
  console.log('error 请求拦截 : ', error)
  return promise.reject(error);
 });
 instance(options)
  .then(response => {
   const res = response.data;
   if (res.errorcode != status.success) {
   switch (res.errorcode) {
    case status.net_err: {
    errorprompt(res.errormsg)
    reject(res)
    break;
    }
    case status.biz_err: {
    errorprompt(res.errormsg)
    reject(res)
    break;
    }
    case status.no_auth: {
    errorprompt(res.errormsg)
    let session = require("storejs")
    if (ismanager(options)) { // 管理端
     session.remove("managerusertoken")
     router.push({path: '/manager/login'})
    } else {
     session.remove("clientusertoken")
     router.push({path: '/client/login'})
    }
    reject(res)
    break
    }
   }
   }
   closeloading();
   resolve(res);
  }).catch(error => {
   closeloading();
   errorprompt('网络连接错误,请检查您的网络')
   console.log('error', error); // for debug
   reject(error);
  });
 });
}
function commonbizheader (ismanager) {
 let session = require("storejs");
 let params = {}
 params['ua'] = window.navigator.useragent.tolowercase()
 params['cv'] = '123456'
 params['ws'] = window.screen.height + '*' + window.screen.width
 params['token'] = "123456"
 params['os'] = window.navigator.appcodename
 if (ismanager) {
 params['token'] = session.get('managerusertoken') // 管理 - 用户令牌
 } else {
 params['token'] = session.get('clientusertoken') // 用户 - 用户令牌
 }
 params['app'] = 'kind'
 let uuid = session.get('pkey')
 if (!uuid) {
 uuid = getuuid()
 window.localstorage.setitem('pkey', uuid)
 }
 return encodeuricomponent(json.stringify(params))
}
function ismanager(options) {
 return options && options.url && options.url.indexof("/api/worker") != -1
}
/**
 * 获取uuid
 * @returns {string}
 */
export function getuuid() {
 let len = 32 // 32长度
 let radix = 16 // 16进制
 let chars = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'.split('')
 let uuid = []
 let i
 radix = radix || chars.length
 if (len) {
 for (i = 0; i < len; i++) {
  uuid[i] = chars[0 | math.random() * radix]
 }
 } else {
 var r
 uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
 uuid[14] = '4'
 for (i = 0; i < 36; i++) {
  if (!uuid[i]) {
  r = 0 | math.random() * 16
  uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
  }
 }
 }
 return uuid.join('').tolowercase()
}

这是在vue的项目中:在api中调用方法如下(react刚开始学,还在做简单demo)

import {fetch} from 'api/fetch'
export const callauthcode = (userphone) => {
 return fetch({
 url: '/api/auth/code',
 method: 'post',
 data: ({
  userphone: userphone,
 }),
 })
}

因为我们这边的后台要求严格区分get/post请求,所以封装的方法调用中必须带有method,如后台已经处理好,全部可进行post请求,则可以参照axios官网里面将方法全部改为.post

关于fetch方法的说明:主要进行封装了请求拦截,响应拦截,默认请求体由json格式转换form格式,当然,这些都是在axios官网里可以找到的,不过是集合下了而已

关于请求头部分请不要直接套用,这是我们这边后台要求特殊配置的,后台接口三端共用,必须区分是哪里在调用

以上这篇基于axios封装fetch方法及调用实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。