基于vue-cli2.x封装axios

src目录

axios.js

import axios from 'axios'
import { Indicator, Toast } from 'mint-ui'

// request 拦截器
axios.interceptors.request.use(config => {
  Indicator.open({ text: '加载中...', spinnerType: 'snake' })
  return config
}, err => {
  Indicator.close();
  Toast({ message: '请检查您的网络连接并重试', duration: 2000, className: 'mToast' })
  return Promise.reject(err)
})

// response 拦截器
axios.interceptors.response.use(
  config => {
    Indicator.close();
    return config
  }, err => {
    Indicator.close();
    Toast({ message: '请检查您的网络连接并重试', duration: 2000 })
    Promise.reject(err)
  }
)

export default axios

config.js

// 在 axios中,利用QS包装data数据
import Qs from 'qs'
const config = {
  baseURL: 'http://www.****.top:8888/',
  url: '',
  method: 'get',
  params: {},
  data: {},
  timeout: 100000,
  withCredentials: false,
  responseType: 'json',
  headers: {
    'Content-Type': 'application/json'
  },
  maxContentLength: 10000,
  maxRedirects: 5,
  transformResponse: [function(data) {
    return data
  }],
  paramsSerializer: function(params) {
    return Qs.stringify(params)
  },
  onUploadProgress: function(progressEvent) {
    // console.log('onUploadProgress...');
  },
  onDownloadProgress: function(progressEvent) {
    // console.log('onDownloadProgress...');
  }
}

export default config

fetch.js

// 引入 请求拦截 配置
import $axios from "./axios"
// 引入 请求参数 配置
import config from './config'

config.headers.Authorization = window.sessionStorage.getItem('token') || ''

// 封装成自己的方法
fetch = async function(url, method, request, other) {
  let response
  if(method == 'post') {
    config.data = request
    response = await $axios.post(url, request, config)
  } else if(method == 'get') {
    config.params = request
    response = await $axios.get(url, config)
  }
  console.log(response)
  return response
}

export default fetch

测试

.vue文件

<template>
  <div>
    <hr>
    <h1 @click="postJson">login-postJson</h1>
    <hr>
    <h1 @click="getJson">getJson</h1>
    <hr>
    <h1 @click="getUserList">getUserList</h1>
  </div>
</template>

<script>
import mix from './Apitest-mixins.ts'

export default {
  mixins: [mix]
}
</script>

.ts文件

import fetch from '../../request/fetch.js'
export default {
  methods: {
    async postJson() {
      const params = {
        "username": "admin",
        "password": "123456"
      }
      let { data: res } = await fetch('/login', 'post', params)
      window.sessionStorage.setItem('token', res.data.token)
      console.log(res)
    },
    async getJson() {
      let { data: res } = await fetch('/roles', 'get')
      console.log(res)
    },
    async getUserList() {
      let params = {
        query: 'a',
        pagenum: 2,
        pagesize: 10
      }
      const { data: res } = await fetch('/users', 'get', params )
      console.log(res)
    }
  }
}

遗留bug

请求头???百度了2天,问了同事也没有解决了,自己都奔溃了

Vue.js(18)之 axios简单封装的更多相关文章

  1. axios简单封装

    写在最前面 新手前端刚刚接触vue,感觉真的好用.项目中需要使用axios,然后学习了一下.借鉴网上一些大佬的经验,现在分享一下axios的简单封装,如果有什么错误的地方,请大家指出. axios安装 ...

  2. Vue.js的安装及简单使用

    一.Vue简介 二.Vue.js的安装 2.1.npm安装 2.1.1.node.js介绍及安装 简介: 简单的说 Node.js 就是运行在服务端的 JavaScript. Node.js 是一个基 ...

  3. vue-axios当只调用vue.js又需要axios请求多时

    可以将axios方法封装一个函数 (function () { ASK = { get:function (url,data,succFun,errFun) { axios.get(url,{ par ...

  4. vue axios 简单封装以及思考

    先安装 axios npm install axios axios的详细介绍以及用法 就不多说了请 移步 github ➡️  https://github.com/axios/axios 下面是简单 ...

  5. vue.js中使用Axios

    Axios为vue2.0官方推荐HTTP请求工具,之前的是vue-resource 在使用的过程中总结了两种使用方式: 1.和vue-resource使用类似 引入:import axios from ...

  6. 在使用Vue.js中使用axios库时,遇到415错误(不支持的媒体类型(Unsupported media type))

    知识点:vue2.0中使用axios进行(put,post请求时),遇到415错误 解决办法:在axios的第三个参数config中,设置请求头信息'Content-Type': 'applicati ...

  7. vue.js提交按钮时简单的if判断表达式示例

    简单的业务需求如下,看图说话 1:当充值金额没有填写的时候,会有Toast小弹框提示"请输入有效的充值金额" if (!this.money) { console.log('mon ...

  8. Vue.js(20)之 封装字母表(是这个名字吗0.0)

    HTML结构: <template> <div class="alphabet-container"> <h1>alphabet 组件</ ...

  9. Vue.js(19)之 封装calendar组件

    效果 需求 1.实现一个日历组件,如图: 2.显示某天的事项: 3.事项是模拟父组件请求接口返回的,数据格式如下: [ { id: '232', date: '2019-06-01', info: ' ...

随机推荐

  1. leetcode142 Linked List Cycle II

    """ Given a linked list, return the node where the cycle begins. If there is no cycle ...

  2. (编辑状态下)Reset及OnValidate使用

    using UnityEngine; using System.Collections; public class Demo : MonoBehaviour { #if UNITY_EDITOR vo ...

  3. 吴裕雄 Bootstrap 前端框架开发——Bootstrap 辅助类:清除浮动1

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  4. 2017北京网络赛 J Pangu and Stones 区间DP(石子归并)

    #1636 : Pangu and Stones 时间限制:1000ms 单点时限:1000ms 内存限制:256MB 描述 In Chinese mythology, Pangu is the fi ...

  5. jsp el表达式判空

    https://www.cnblogs.com/sxdcgaq8080/p/8119186.html

  6. vue - 子组件向父组件 传递方法和参数

    1,子组件 TodoItem.vue  : <template>   <div class="todo-item" :class="{'is-compl ...

  7. 使用BP拦截POST型请求包

    1.安装phpstudy并下载wordpress 文件,安装在phpstudy的www目录下 phpstudy下载地址:https://www.xp.cn/download.html wordpres ...

  8. phpStudy隐藏后门预警

    1.事件背景 近日,使用广泛的PHP环境集成程序包phpStudy被公告疑似遭遇供应链攻击,程序包自带PHP的php_xmlrpc.dll模块隐藏有后门,安恒应急响应中心和研究院随即对国内下载站点提供 ...

  9. 微信小程序IOS真机调试发生了SSL 错误,无法建立与该服务器的安全连接

    小程序 真机调试 IOS request:fail 发生了SSL 错误,无法建立与该服务器的安全连接,解决方法服务器中打开Powerhell,执行以下代码,然后重启服务器 # Enables TLS ...

  10. lsof(查看端口)

    简介 简介 lsof(list open files)是一个列出当前系统打开文件的工具.在linux环境下,任何事物都以文件的形式存在,通过文件不仅仅可以访问常规数据,还可以访问网络连接和硬件.所以如 ...