vue中关于(axios)

 1-axios

1.1-axios的介绍

 第三方的http类库

- 底层基于ES6中promise进行封装的

- 底层依然基于XMLHttpRequest异步对象

 1.1.1-安装

npm i axios -S

1.2-axios发送数据请求

1.2.1-get请求

通过axios发送get请求

  axios({

    method: 'GET',    // 请求方式

    url: '/user', // 接口地址

    params:{        // get请求参数

        name:'zs',    

        age:20

    }  

  }).then(res=>{    // 成功处理函数

      console.log(res);

  })

- 通过axios.get()方法发送get请求

  axios.get('数据接口地址',{

      // get请求的参数

      params:{

          name:'zs',

          age:20

      }

  }).then(res=>{    // 成功处理函数

      console.log(res);

  })

1.2.1-post请求

- 通过axios发送post请求

  axios({

    method: 'POST',   // 请求方式

    url: '/user',     // 接口地址

    data:{        // post请求参数, 请求体

        name:'zs',    

        age:20

    }

  }).then(res=>{      // 成功处理函数

      console.log(res);

  })

- axios.post

  axios.post('数据接口地址',{ 

      name:''   // 请求体

  }).then(res=>{  // 成功处理函数

      console.log(res);

  })

  1.3-拦截器

 1.3.1-请求拦截器

- 对所有的请求都会进行拦截

  axios.interceptors.request.use(function(config){

      console.log(config,'interceptors.request');

      // 自定义的请求头

      config.headers.auth='abcd';

      return config;

  })

  1.3.2-响应拦截器

 对服务端的每一次响应进行拦截

  axios.interceptors.response.use(function(response){

      console.log(response,'interceptors.response');

      if(response.status===200){

          return response.data

      }

      return response;

  });

 1.4-axios的全局配置

1. 全局配置基础域名(baseURL)

   axios.defaults.baseURL='http://localhost:3333'

2. 配置请求头

   axios.defaults.headers.自定义请求头="请求头内容"

1.5-axios.create()方法

- 创建一个axios的实例对象

  import Vue from 'vue';

  import axios from 'axios';

  // 创建一个实例

  const instance=axios.create({

      baseURL:'http://localhost:3333',

      headers:{

          token:'123456abc'

      }

  });

  // 请求拦击器

  instance.interceptors.request.use(function(config){

      console.log(config);

      return config;

  });

  

  // 响应拦截器

  instance.interceptors.response.use(function(response){

      console.log(response);

      return response.data;

  });

  

  // 将axios的实例挂在到vue的原型对象上

  Vue.prototype.$http=instance;

  

  // 导出

  export default instance;

   

   














 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值