axios

一、说明

Axios 是一个基于 Promise 的 HTTP 库,用于浏览器和 node.js中。

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

二、安装

在 Vue 项目中

npm install axios

三、常用 api 说明

可使用 万能地址 发送做测验。客户端使用即在原来 ajax 代码替换成 axios。

1、get 请求  axios.get(url[, config])

// 为给定 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);
  });

axios 对象调用 get 方法,.then() 成功回调,.catch() 失败回调。

get 方法也可以把url中的参数提出来单独放到一个对象中。

2、post请求  axios.post(url[, data[, config]]) 

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

3、通用请求 axios(config),通过向 axios 传递相关配置config对象来创建请求

axios({
  methods: 'post',
  url: 'http://jsonplaceholder.typicode.com/users',
  data: {
  name: 'qiurx'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })

4、执行多个并发请求

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

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

axios.all([getUserAccount(), getUserPermissions()])   //两个请求放到数组中传递给all()
  .then(axios.spread(function (acct, perms) {   //多个请求都发送完毕,拿到返回的数据
    // 两个请求现在都执行完成
  }));

axios中的all()方法,传入一个数组,数组元素即为函数调用,函数中即为请求调用。
然后,then()回调方法中调用axios自己的spread()方法。

四、axios 在 Vue 中的使用

1、then()中的 resp 返回包含头、状态、data数据等等,真正返回数据在此对象中的data

2、this的指向问题:$axios没有定义或者 get()没有定义,是因为this不是指向vue实例。可以通过const _this = thisbind(this)把 this 传递进去。

posted @ 2020-11-04 20:27  Nora西  阅读(97)  评论(0)    收藏  举报