Encapsulation of axios in the vue project

1. Installation

npm install axios

2. Introduction

Generally, I will create a network folder in the src directory to create a
config.js (used to encapsulate axios) and an api.js (used to unify the management interface)

Three, configure axios in config.js

// 引入axios
import axios from 'axios'
// 引入router路由
import router from '@/router/index'
// 引入elementUI中loading和messageBox
import {
    
    
  Loading,
  MessageBox
} from 'element-ui'
// cookie
import {
    
    
  setCookie,
  getCookie
} from '@/common/cookie.js'

// ===== axios 配置 ======

//post请求头的设置
//post请求的时候,我们需要加上一个请求头,所以可以在这里进行一个默认的设置,即设置post的请求头为application/x-www-form-urlencoded;charset=UTF-8
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

 
// 设置请求超时
axios.defaults.timeout = 600000

// 环境的切换
axios.defaults.baseURL = process.env.API_ROOT

var loadinginstace  // 这里是loading

// http request 拦截器
axios.interceptors.request.use(
  config => {
    
    
    document.cookie.split('; ').map(item => {
    
    
      if (item.split('=')[0] === 'opadminToken') {
    
    
        config.headers.token = getCookie().opadminToken
      }
    })
    // element ui Loading方法
    loadinginstace = Loading.service({
    
    
      lock: true,
      text: '请求中……',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    return config
  },
  err => {
    
    
    MessageBox({
    
    
      title: '错误',
      message: '请求超时',
      callback: action => {
    
    
        loadinginstace.close()
      }
    })
    return err
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    
    
    if (response.data.messageCode === 'MSG_1001') {
    
    
      setCookie('opadminToken', response.headers.token, 15)
    } else if (response.data.messageCode === 'MSG_2001') {
    
    
      router.push('/')
    }
    loadinginstace.close()
    return response
  },
  error => {
    
    
    if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
    
    
      MessageBox({
    
    
        title: '错误',
        message: '请求超时',
        callback: action => {
    
    
          loadinginstace.close()
        }
      })
    }

    return error
  }
)

export default axios

Fourth, set up unified management of API interface in api.js

// 引入配置好的axios 并命名为request
import request from './config'

// 设置post请求
const userLoginRequest = p => request.post('/xxx/login', p) // 登录

// 设置get请求
const queryOrder = p => request.get(`/xxx/queryOrder${
      
      p}`) // 查询订单详情

// 设置get请求
const queryLogistics = p => request.get('/xxx/queryLogistics', p) // 查询物流信息

// 设置请求的responseType
const getExcel = ids => request.get('/xxx/getMerchantAuditListExcel', {
    
    
  params: {
    
    
    ids
  },
  responseType: 'blob'
}) // 导出excel

// 导出接口
export {
    
    
userLoginRequest ,
queryOrder ,
queryLogistics ,
getExcel 
}

Five, use the interface

// 引入接口方式
import {
    
    userLoginRequest ,queryOrder ,queryLogistics ,getExcel} from'@/network/api'

// post请求
userLoginRequest(){
    
    
	let data = {
    
    
		userName:'xxx',
		password:'xxx'
	}
	userLoginRequest(data).then(res=>{
    
    
		console.log(res)
	})
}

// get请求
queryOrder(){
    
    
	queryOrder(`?id=${
      
      this.id}`).then(res=>{
    
    
		console.log(res)
	})
}

// get请求
queryLogistics(){
    
    
	let data = {
    
    
		name:'xxx',
		age:'xxx'
	}
	queryLogistics({
    
    params:data}).then(res=>{
    
    
		console.log(res)
	})
}
Web front-end technology exchange QQ group: 327814892

Guess you like

Origin blog.csdn.net/qq_43327305/article/details/103333015