当前位置: 移动技术网 > IT编程>开发语言>JavaScript > axios

axios

2018年09月18日  | 移动技术网IT编程  | 我要评论

最近通过 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'
    }
  }
}

 

 

参考

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网