vue封装axios

文档客
• 阅读 5037

1、目录结构

vue封装axios

2、配置

2.1 vue.config.js

用@代替/src这个目录,避免写错路径

const path = require('path')
const resolve = dir => {
  return path.join(__dirname, dir)
}
module.exports = {
    devServer: {
        open: true,
        host: 'localhost',
        port: 8080,
        https: false,
        hotOnly: false,
        disableHostCheck: true,
        proxy: {
            // 配置跨域
            '/api': {
                target: 'http://localhost:8000/',
                ws: true,
                changOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        },
        before: app => { }
    },
    chainWebpack: config => {
      // key,value自行定义
      config.resolve.alias.set('@', resolve('src')) 
    }
};

2.2 config.js

export default {
  // 配置显示在浏览器标签的title
  title: '沉潜',
  
  // token在Cookie中存储的天数,默认1天
  cookieExpires: 1,
  
  // 是否使用国际化,默认为false 如果不使用,则需要在路由中给需要在菜单中展示的路由设置meta: {title: 'xxx'} 用来在菜单中显示文字
  useI18n: true,
  
  // api请求基础路径  
  baseUrl: {
    dev: 'http://localhost:8000/',
    pro: 'https://xxx.com/api/'
  },
  
  // 默认打开的首页的路由name值,默认为home
  homeName: 'home',
  
  // 需要加载的插件
  plugin: {
    'error-store': {
      // 设为false后不会在顶部显示错误日志徽标
      showInHeader: true,
      // 设为true后在开发环境不会收集错误信息,方便开发中排查错误
      developmentOff: true
    }
  }
}

2.3 request.js

import HttpRequest from '@/utils/axios'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro
const axios = new HttpRequest(baseUrl)
export default axios

2.4 axios.js

import axios from 'axios'

class HttpRequest {

  constructor (baseUrl) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        Authorization: ''
      }
    }
    return config
  }
  
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启,因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })

    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data } = res
      if (typeof data === 'object') {
        // 自己处理
      }
      return data
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
        console.log(errorInfo)
      }
      return Promise.reject(error)
    })
  }
  
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest

2.5 api.js

import axios from '@/utils/request'
export const insert = (data) => {
  return axios.request({
    url: '/insert',
    method: 'post',
    data
  })
}
export const update = (data) => {
  return axios.request({
    url: '/update',
    method: 'post',
    data
  })
}
export const getList = (params) => {
  return axios.request({
    url: '/getList',
    method: 'get',
    params
  })
}

3、使用

import { getList, update } from '@/api/api'
test () {
  getList({ limit: 10, offset: 1 }).then(res => {
    if (res.status === 200) {
      console.log(res)
    }
  })
  update({ name: '沉潜', userId: 1 }).then(res => {
    if (res.status === 200) {
      console.log(res)
    }
  })
}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
梦
4年前
微信小程序new Date()转换时间异常问题
微信小程序苹果手机页面上显示时间异常,安卓机正常问题image(https://imghelloworld.osscnbeijing.aliyuncs.com/imgs/b691e1230e2f15efbd81fe11ef734d4f.png)错误代码vardate'2021030617:00:00'vardateT
Stella981 Stella981
3年前
List的Select 和Select().tolist()
List<PersondelpnewList<Person{newPerson{Id1,Name"小明1",Age11,Sign0},newPerson{Id2,Name"小明2",Age12,
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
3年前
ELK学习笔记之配置logstash消费kafka多个topic并分别生成索引
0x00 filebeat配置多个topicfilebeat.prospectors:input_type:logencoding:GB2312fields_under_root:truefields:添加字段
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
3年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
3年前
MBR笔记
<bochs:100000000000e\WGUI\Simclientsize(0,0)!stretchedsize(640,480)!<bochs:2b0x7c00<bochs:3c00000003740i\BIOS\$Revision:1.166$$Date:2006/08/1117
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
5个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(