vue 的 axios 进行封装

 request.js // 封装get post 各类请求文件

//第一步

import axios from 'axios'
axios.defaults.baseURL = "/api/"
// http请求拦截器请求头
axios.interceptors.request.use(config => {
  let token = sessionStorage.getItem('mytoken'); //------
  if (!token) {
    // return config
    token = 'dG9rZW4tMS0w'
  }
  config.headers['Authorization'] = token; //-------
  return config
}, error => {
  return Promise.reject(error)
});
// http响应拦截器响应
axios.interceptors.response.use(res => { // 响应成功关闭loading
  return res.data
}, error => {
  return Promise.reject(error)
})
/**
 *   get方式
 *   url {String} api接口地址
 *   params {Object} 接口参数
 */
function get(url) {
  return function(params) {
    return axios.get(url, { params }).then(res => {
      return res
    })
  }
}
/**
 *   get方式下载二进制流文件
 *   url {String} api接口地址
 *   params {Object} 接口参数
 */
function getDownload(url) {
  return function(params) {
    return axios.get(url,{params:params, responseType: 'arraybuffer'}).then(res => {
      return res
    })
  }
}
/**
 *   post方式
 *   url {String} api接口地址
 *   params {Object} 接口参数
 */
function post(url) {
  return function(params) {
    const formData = new FormData()
    for (let key in params) {
      let val = params[key]
      formData.append(key, val)
    }
    return axios.post(url,params).then(res => {
      return res
    })
  }
}

export { get, post ,getDownload}

//第二步引入上面写的文件

import {
  get,
  post,
  getDownload
} from '../request'

const getProductYieldReport = post('/xkec/getProductYieldReport')//二期选厂生产产量报表
const expProductYieldReport = getDownload('/xkec/expProductYieldReport') //导出二期选厂生产产量报表
const getProductGroupReport = post('/xkec/getProductGroupReport')//班组报表
const expProductGroupReport = getDownload('/xkec/expProductGroupReport')//导出班组报表
const getAccumulativeTotalReport = post('/xkec/getAccumulativeTotalReport')//累计报表
const expAccumulativeTotalReport = getDownload('/xkec/expAccumulativeTotalReport')//导出累计报表
const alarmScrollList = post('/xkec/alarmScrollList')//报警跑马灯数据(已废弃)
const getEquipmentStatus = post('/xkec/getEquipmentStatus') //设备列表
const getEquipmentInfoById = post('/xkec/getEquipmentInfoById')//设备信息
const getArea = post('/xkec/getArea')//获取区域
const getEquipmentInfoList = post('/xkec/getEquipmentInfoList') //控制图详情

export {
  getProductYieldReport,
  expProductYieldReport,
  getProductGroupReport,
  expProductGroupReport,
  getAccumulativeTotalReport,
  expAccumulativeTotalReport,
  alarmScrollList,
  getEquipmentStatus,
  getEquipmentInfoById,
  getArea,
  getEquipmentInfoList
}

//第三步如何使用

import {alarmScrollList,getEquipmentStatus,getArea} from "../../api/modules/api"


methods:{
         _alarmScrollList(){
           let params = {
             tokenId:getUserInfo().token,
             type:1
           }
           alarmScrollList(params).then((res)=>{

           })
         },
}

 

你可能感兴趣的:(vue 的 axios 进行封装)