前端之美-VueJs

axios 获取后台数据

2019-03-25  本文已影响359人  樊小勇

什么是axios

axios的特性

1.可以从浏览器中创建XHR对象
2、可以从nodeJS中创建HTTP请求
3、支持Promise
4、可以拦截请求和响应
5、可以转换请求数据和响应数据
6、可以取消请求
7、可以自动转换JSON数据
8、客户端支持防御XSRF

获取数据:
路径为后台数据接口
在用axios获取后台数据时,
  get  function(){
      var url = '路径'
    axios.get(url,{params:参数}).then(function(储存后台数据的变量:A){    //then为成功后的回调
        对象名.渲染页面的函数名(A.data)                     // data是在使用axios的时候,axios给数据添加了一个data来封装获得的数据,
    }).catchcatch(function (用来储存错误信息的变量:error){ // 捕捉错误
      alert(error)                                        // 请求失败之后,执行这个函数
    })
    }
axios.get('index.php')
  .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);
  });

当然,也可以把参数数据直接写到URL中

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
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) {
    // acct为第一个请求的结果,perms为第二个请求的结果
  }));
上一篇 下一篇

猜你喜欢

热点阅读