vue学习日记12

Axios

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

promise: https://www.liaoxuefeng.com/wiki/1022910821149312/1023024413276544

前端发送请求的有三种,ajax,axios,fetch。

Vue1.x中,官方推荐使用的ajax库是vue-resource。到了Vue2.x,官方推荐的ajax库改为了Axios,按照说法是因为已有一个更完备的轮子,就不需要造一个新的。

第一步安装

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) {
    // 两个请求现在都执行完成
  }));

在我们使用axios的时候,我们可以添加请求拦截器,

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

例如在请求头中添加token。我们就可以在请求拦截器中完成。

import axios from 'axios'
var service = axios.create({
  timeout: 15000
})
// 请求拦截器,给所有的请求加上token
// 添加请求拦截器
service.interceptors.request.use((config) => {
  let token = localStorage.getItem('token')
  config.headers = {
    'Authorization': 'Bearer ' + token
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})
export default service

响应拦截器

service.interceptors.response.use(response => {
  // 对响应数据做点什么
  return response
}, error => {
  // 对响应错误做点什么
  return Promise.reject(error)
})
原文地址:https://www.cnblogs.com/wangnothings/p/12546383.html