Vue 通过 axios 发起网络请求

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

特点

  • 支持浏览器和node.js
  • 支持promise
  • 能拦截请求和响应
  • 能转换请求和响应数据
  • 能取消请求
  • 自动转换JSON数据
  • 浏览器端支持防止CSRF(跨站请求伪造)

安装和使用

npm 安装

$ npm install axios

bower 安装

$ bower install axios

使用 cdn:(引入在线地址免去下载导包
<script src="https://unpkg.com/axios/dist/axios.min.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) {
    
    
    // 两个请求现在都执行完成
  }));

axios 发起 API 请求

axios({
    
    
  url: 'https://xxxx',
  method: 'get', // 请求方式 get 和 post
  params: {
    
    
  	// 模拟参数
    id // id:id
  }
}).then(res => {
    
    
  // 分析请求到的数据
})

点击查看 axios中文说明

猜你喜欢

转载自blog.csdn.net/qq_43562262/article/details/105900259
今日推荐