zoukankan      html  css  js  c++  java
  • 封装axios

    import axios from 'axios'
    // import store from '@/vuex/store.js'
    import router from '../router'
    import qs from 'qs'
    
    
    const instance = axios.create({});
    
    instance.defaults.baseURL = 'http://mini.youhulianchuang.com';
    instance.defaults.timeout = 5000;
    instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    instance.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest';
    instance.defaults.headers.post['top-token'] = 'top-token';
    instance.defaults.responseType = 'json';
    
    
    
    
    // 请求拦截
    instance.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
      console.log('请求拦截')
      console.log(config)
        return config;
    
      }, function (error) {
        // 对请求错误做些什么
        // alert('网络错误,请稍后再试');
    
      });
    
    // 对传给后台的数据做统一的操作
    instance.defaults.transformRequest=[function (data) {
      // 对 data 进行任意转换处理
    
      Object.assign(data,{age:21})
      console.log(data)
      return data;
    
    }]
    
    // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
    instance.defaults.transformResponse=[function (data) {
      // 对 data 进行任意转换处理
      console.log(data)
    
      return data;
    }]
    
    	// 添加响应拦截器
    instance.interceptors.response.use(function (response) {
      console.log('添加响应拦截器')
        console.log(response)
      	return response.data;
    
    	}, function (error) {
      	// 对响应错误做点什么
    
    	if(error.response) {
    
    	}
      	// return Promise.reject(error);
    });
    
    
    export default {
    install: function(vm){
        vm.prototype.$instance = instance;
    }

     2、调用

    在main.js中引入封装文件并当作vue插件使用

    import Utile from './lib/utils'

    Vue.use(Utile)

    3、在模块中使用get请求

    this.$instance.get(`Employee/Detail/${this.$route.query.userId}`
                    ).then((res)=>{    
                        console.log(res.data)
                        if(res.data.code == 0){
                           操作
                     }
                     else{

    }

    })

    4、在模块中使用post请求

     this.$instance.post("/enumList",
                      params).then(({ data: { data = []} = {} })=>{
                      console.log(data)
                    })
                    .catch((error) =>{
                      console.log(error);
                    });
          })

    注:params是参数

  • 相关阅读:
    计算机入门知识
    iOS学习之-开机引导图
    学习笔记之09-空指针和野指针
    学习笔记之08-self关键字
    学习笔记之07-自定义构造方法和description方法
    学习笔记之06-点语法
    学习笔记之05-第一个OC的类
    学习笔记之04-第一个OC程序解析
    学习笔记之03-第一个OC程序
    hdoj1016 [dfs]
  • 原文地址:https://www.cnblogs.com/zhouxiaobai/p/9340211.html
Copyright © 2011-2022 走看看