码迷,mamicode.com
首页 > 移动开发 > 详细

axios

时间:2018-09-18 17:12:29      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:proxy   rmi   first   pos   port   post   div   特性   tab   

最近通过 Vuejs 重构旅游页面项目使用到 axios 获取数据。对照官方文档,简要记录一些 axios 的使用方法和特性,方便日后参考和查阅。

axios

基于 promise 用于浏览器和 node.js 的 http 客户端

安装

npm 安装

npm install axios

 

通过 cdn 引入

<script src="https://cdn.bootcss.com/axios/0.18.0/axios.js"></script>

 

用法

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

 

 

其他

设置 mock数据 开发环境转发代理

在 Vue-cli 脚手架工具之下
设置 config 文件夹下的 index.js
设置 module.exports 下 dev 的 proxyTable 代理
webpack-dev-server 工具会自动将 /api 替换成 /static/mock
从而达到不用改动项目代码的目的

proxyTable: {
  ‘/api‘: {
    target: ‘http://localhost:8080‘,
    pathRewrite: {
      ‘^/api‘: ‘/static/mock‘
    }
  }
}

 

 

参考

axios 全攻略

axios

标签:proxy   rmi   first   pos   port   post   div   特性   tab   

原文地址:https://www.cnblogs.com/evenyao/p/9669636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!