vue-cli下封装axios

由于性能问题,今后开发采用webpack打包,故ajax采用axios请求方式
axios安装:npm install axios --save
以下是封装文件
以下是封装文件位置
以下是common.js

import axios from 'axios'
var instance = axios;
//默认post请求为json格式
instance.defaults.headers.post["Content-Type"] = 'application/json; charset=utf-8';

//区分开发生产环境
const identityBaseUrl = (location.href.indexOf('localhost') > 0 || location.href.indexOf('dev') > 0) ? "xxx":"xxx"
//token,deviceId,version
var accessToken = "xxx";
var client = "a8cd6455-6f08-46fb-ab1a-3adf66b83125-d9267e15-e7a9-4369-b441-4a35e19d2ca0";
var device = "104";
var headers = {};
if (client && client.length>0 && device && device.length>0){
  headers = {"Client-Version" : device,"Device-Id":client};
}
if (accessToken && accessToken.length > 0) headers.Authorization = "Bearer " + accessToken;
export default {
    getApi(url,params= {}) {
        return new Promise((resolve, reject) => {

           axios.get(identityBaseUrl+url,{
                headers : headers,
                params : params
           }).then((res) =>{
                if (res.errCode == 6){

                }
                resolve(res.data);
            }).catch((err) =>{
                  reject(err)
            })
        })
    },
    postApi(url,params = {}) {
        return new Promise((resolve,reject) => {
            axios.post(identityBaseUrl+url,{
              headers : headers,
              params : params
            }).then((res) =>{
                  resolve(res.data)
            }).catch((err) =>{
                  reject(err)
            })
        })
    }
}


appApi.js

import $ajax from "./common"
let ajax = {};
ajax.getHelps = (params) =>{
    return $ajax.getApi('/uapi/helps',params)
  }
export default ajax

vue中引用






你可能感兴趣的:(vue-cli下封装axios)