当前位置: 移动技术网 > IT编程>脚本编程>vue.js > 详解axios 全攻略之基本介绍与使用(GET 与 POST)

详解axios 全攻略之基本介绍与使用(GET 与 POST)

2017年12月12日  | 移动技术网IT编程  | 我要评论

再世人生艳遇记,jusched,巴厘岛酒店排名

axios

axios 是一个基于 promise 的 http 客户端,专门为浏览器和 node.js 服务

vue 2.0 官方推荐使用 axios 来代替原来的 vue request,所以这里介绍一下 axios 的功能和基本的使用方法,希望能够对各位所有帮助。^_^

功能

  • 在浏览器中发送 xmlhttprequests 请求
  • 在 node.js 中发送 http 请求
  • 支持 promise api
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换 json 数据格式
  • 客户端支持防范 xsrf 攻击

浏览器支持

axios 能够支持 ie7 以上的 ie 版本,同时能够支持大部分主流的浏览器,需要注意的是,你的浏览器需要支持 promise,才能够使用 axios。所以比较好的做法是先安装 polyfill,然后再使用 axios。

安装

using npm:

$ npm install axios

using bower:

$ bower install axios

using cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用

这里以 vue 为例:在 npm 中安装 axios 之后,需要在 main.js 文件中引用 package

import axios from 'axios'

然后全局绑定

vue.prototype.$http = axios

然后可以在 .vue 文件中使用 $http 来代替 axios

get

// make a request for a user with a given id 
axios.get('/user?id=12345')
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });

// optionally the request above could also be done as 
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) {
  // both requests are now complete 
 }));

当然,axios 的功能还包括 axios api、interceptor 等等,这里想要详细了解的可以查看官方文档:axios,后面陆续会介绍下 interceptor 的使用和各类参数的配置。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网