Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止 CSRF/XSRF
安装Axios
我们直接使用npm install来进行安装。
npm install axios --save
由于axios是需要打包到生产环境中的,所以我们使用--save来进行安装。 也可以选择使用cnpm来安装,加快安装速度。
引入Axios
只需要在需要的vue文件中引入axios就可以。
import axios from 'axios'
使用
发送一个GET
请求
//通过给定的ID来发送请求 axios.get('/user?ID=12345') .then(function(response){ console.log(response); }) .catch(function(err){ console.log(err); }); //以上请求也可以通过这种方式来发送 axios.get('/user',{ params:{ ID:12345 } }) .then(function(response){ console.log(response); }) .catch(function(err){ console.log(err); });
发送一个POST
请求
axios.post('/user',{ firstName:'Fred', lastName:'Flintstone' }) .then(function(res){ console.log(res); }) .catch(function(err){ console.log(err); });
一次性并发多个请求
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){ //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果 }))