vue项目中对axios的封装

一、安装

npm install axios

二、引入

一般我会在src目录上创建一个network文件夹
network文件夹中创建一个config.js (用来封装axios)和一个api.js(用来统一管理接口)

三、config.js 中配置axios

// 引入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

四、api.js 中设置API接口的统一管理

// 引入配置好的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 
}

五、使用接口

// 引入接口方式
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前端技术交流QQ群:327814892

猜你喜欢

转载自blog.csdn.net/qq_43327305/article/details/103333015