axios

来源:互联网 发布:淘宝镜子 编辑:程序博客网 时间:2024/06/05 16:52

综合描述

    

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


特点:

1.  从浏览器获取 XMLHttpRequests 对象

2.  使用node.js发送http请求

3.  支持Promise的API

4.  拦截请求和响应

5.  对请求和相应的数据做处理

6.  撤销请求

7.  自动解析JSON数据

8.  防止客户端XSFR攻击


浏览器支持情况:

安装:

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) {    // Both requests are now complete  }));

axios API

请求可以通过axios做一些配置

axios(config)

// 发送一个POST请求axios({  method: 'post',  url: '/user/12345',  data: {    firstName: 'Fred',    lastName: 'Flintstone'  }});
// GET请求获取一个远程的图片axios({  method:'get',  url:'http://bit.ly/2mTM3nY',  responseType:'stream'})  .then(function(response) {  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))});

axios(url[,config])

// 发送一个get请求(默认请求方式)axios('/user/12345');


请求方法别名

所有支持的请求方法都有一个方便的别名

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
注意:当时用别名方法时,url,方法和数据属性不需要在config中配置

未完待续