axios从安装到使用的教程

8 篇文章 0 订阅
安装axios:
npm install --save axios
目录结构:

这里写图片描述

红框部分是接口文件:
appApi.js是存放接口的文件
import Vue from 'vue'
import axios from 'axios'

export default {
  // 获取分类
  show_category: function () {
    return axios.post('/point-api-show_category');
  },
  // 获取商品
  get_product: function (data) {
    return axios.post('/point-api-get_product',data);
  }  
}
apiServer.js是设置vue的属性API的:
import Vue from 'vue'
import API from './API/appApi'

Vue.prototype.API = API;
在main.js里引入axios和apiServer.js
import ProtoTypeAPI from './network/apiServer'
import axios from 'axios'
new Vue({
  el: '#app',
  router,
  store,
  axios,
  template: '<App/>',
  components: { App },
  methods: {
    setSessionStorage:function(data) { 
      for(let key in data){
        sessionStorage[key] = data[key];
      }
    },
    setLocalStorage: function(data) { 
      for(let key in data){
        localStorage[key] = data[key];
      }
    }
  }
})
组件里调用接口:
    get_product: function (name,cate_id) {
      this.API.get_product({
        name: name,
        cate_id: cate_id
      }).then((response) => {
          console.dir(response);
      }, (response) => {
          mui.toast('网络错误');
      });
    }
设置拦截器header.js文件,引入了config.js配置文件:
import Vue from 'vue'
import axios from 'axios'
import GLOBAL_CONFIG from './config'

// 设置默认的配置项
const  CONFIG = GLOBAL_CONFIG['GLOBAL_CONFIG'];

axios.defaults.baseURL = CONFIG['API_HOST'];

//添加请求拦截器
axios.interceptors.request.use(function(config){
  // 获取token
  let TOKEN=localStorage.token;
  // 设置token
  if(TOKEN){   
    config.headers['X-ODAPI-Authorization'] = TOKEN;
  }
  // 返回配置项
  return config;

},function(error){
  //请求错误时做些事
  return Promise.reject(error);
});

//添加响应拦截器
axios.interceptors.response.use(function(response){
  // console.log(JSON.stringify(response)); 
  if(response['status'] == 200){
    if(response['data']['error_code'] == 0){
       return response['data']['data'];
    }else{      
      if(response['data'].hasOwnProperty('erron')){
        mui.toast(response['data']['erron']);
      }
      return false;
    }    
  }else{
    mui.toast('网络错误!');
  }

},function(error){
  //请求错误时做些事
  return Promise.reject(error);
})
配置文件config.js
export default { 
    GLOBAL_CONFIG :{
        'API_HOST': '接口地址',
        'base64Header': 'data:image/png;base64,',
        'dataImage':'data:image',
        'db':'odoo3',
    }   
}
  • 3
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值