Vue核心技术-45,Axios-介绍和简单使用

一,前言

vue1.x时,官方推荐HTTP请求工具是vue-resource,但vue2.0将推荐工具改成了axios
加上Vue2.0之后vue-resource不再更新,所以HTTP请求这部分针对axios进行介绍

axios和vue-resource的使用方式相似,
需要注意:axios接口返回的res并不直接是返回的数据,而是经过axios处理过的json对象。
真正的数据在res.data里中
axios.get(url).then((res)=>{
      this.data = res.data
})

下面针对axios开始介绍

二,axios简介

Axios是一个基于promise的HTTP库,可用于浏览器和node.js

功能:

从浏览器中创建 XMLHttpRequests
从 node.js 创建 http 请求
支持 Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换 JSON 数据
客户端支持防御 XSRF

三,安装

$ npm install axios

四,简单使用

GET请求:

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

POST请求:

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

执行多个并发请求:

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求都执行完成后进入
  }));

五,响应结构

请求的响应包含以下信息

{
  // data:服务器响应的数据
  data: {},

  // status:服务器响应的HTTP状态码
  status: 200,

  // statusText:服务器响应的HTTP状态信息
  statusText: 'OK',

  // headers:服务器响应的头
  headers: {},

  // :config:为请求提供的配置信息
  config: {}
}

接收到的响应:

axios.get('/user/12345')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

六,错误处理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 请求已发出,但服务器响应的状态码不在 2xx 范围内
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else {
      // Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

// 使用validateStatus配置选项,自定义HTTP状态码的错误范围。
axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // 状态码在大于或等于500时才会 reject
  }
})

猜你喜欢

转载自blog.csdn.net/ABAP_Brave/article/details/82057417
今日推荐