[转]axios的兼容性处理

来源: https://www.cnblogs.com/leaf930814/p/6807318.html

-------------------------------------------------------

一、简介

看看官网的简介:

“Promise based HTTP client for the browser and node.js” 

译:基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用。

二、特点:

1、在浏览器中发送 XMLHttpRequests 请求;
2、在 node.js 中发送 http请求;
3、支持 Promise API;
4、拦截请求和响应;
5、转换请求和响应数据;
6、自动转换 JSON 数据;
7、客户端支持保护安全免受 XSRF 攻击;

三、安装(官网)

四、应用

1、发送一个get请求

复制代码

axios.get('/welfare', {
  params: {
  giftPackId: 1
  }
 })
 .then(function(res) {
  console.log(res);
 })
 .catch(function (res) {
  console.log(res);
 });

复制代码

2、发送一个post请求

1
2
3
4
5
6
7
8
9
axios.post('/welfare', {
     giftPackId: 1
  })
  .then(function (res) {
    console.log(res);
  })
  .catch(function (res) {
    console.log(res);
  });

3、发送多个并发请求

1
2
3
4
5
6
7
8
9
10
11
12
function getUserAccount() {
  return axios.get('/welfare');
}
 
function getUserPermissions() {
  return axios.get('/getWelfare');
}
 
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // ok
  }));

4、除此之外axios还提供还有如下几种请求方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
axios.request(config)
 
axios.get(url[, config])
 
axios.delete(url[, config])
 
axios.head(url[, config])
 
axios.post(url[, data[, config]])
 
axios.put(url[, data[, config]])
 
axios.patch(url[, data[, config]])

5、兼容性处理

项目中发现,在安卓4.3及以下的手机不支持axios的使用,主要就是无法使用promise。加上以下polyfill就可以了。

项目中安装es6-promise

1
cnpm install es6-promise --save-dev

在axios.min.js开头加上

1
require('es6-promise').polyfill();

ok! 

原文地址:https://www.cnblogs.com/jiemao/p/9475771.html