首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >axios2教程

axios2教程

作者头像
飞狗
发布2018-09-10 11:46:50
3.1K0
发布2018-09-10 11:46:50
举报

axios

axios 是一个基于 promise 的 HTTP 库,用于浏览器和node.js的http客户端,支持拦截请求和响应,自动转换 JSON 数据, 客户端支持防御 XSRFaxios2官方链接

特性

  • 支持浏览器和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获取用户信息
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'
  }
});
// 获取远程图片
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请求(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]])
注释

当使用以上别名方法时,urlmethoddata等属性不用在config重复声明。

同时发生的请求

用于处理并发请求的助手函数

axios.all(iterable)
axios.spread(callback)

创建一个实例

你可以创建一个拥有通用配置的axios实例

axios.creat([config])
var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

实例的方法

以下是所有可用的实例方法,额外声明的配置将与实例配置合并

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。如果没有指定方法,请求将默认为GET。

{
  // `url` 是请求的接口地址
  url: '/user',

  // `method` 是请求的方法
  method: 'get', // 默认值

  // 如果url不是绝对路径,那么会将baseURL和url拼接作为请求的接口地址
  // 用来区分不同环境,建议使用
  baseURL: 'https://some-domain.com/api/',

  // 用于请求之前对请求数据进行操作
  // 只用当请求方法为‘PUT’,‘POST’和‘PATCH’时可用
  // 最后一个函数需return出相应数据
  // 可以修改headers
  transformRequest: [function (data, headers) {
    // 可以对data做任何操作

    return data;
  }],

  // 用于对相应数据进行处理
  // 它会通过then或者catch
  transformResponse: [function (data) {
    // 可以对data做任何操作

    return data;
  }],

  // `headers` 要发送的自定义headers
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // URL参数
  // 必须是一个纯对象或者 URL参数对象
  params: {
    ID: 12345
  },

  // 是一个可选的函数负责序列化`params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // 请求体数据
  // 只有当请求方法为'PUT', 'POST',和'PATCH'时可用
  // 当没有设置`transformRequest`时,必须是以下几种格式
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },

  // 请求超时时间(毫秒)
  timeout: 1000,

  // 是否携带cookie信息
  withCredentials: false, // default

  // 统一处理request让测试更加容易
  // 返回一个promise并提供一个可用的response
  // 其实我并不知道这个是干嘛的!!!!
  // (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth`表示应该使用HTTP Basic auth,并提供凭证。
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // 响应格式
  // 可选项 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // 默认值是json

  // `xsrfCookieName` cookie的名称作为xsrf令牌的值
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` 携带xsrf令牌值的http报头的名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // 处理上传进度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // 处理下载进度事件
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // 设置http响应内容的最大长度
  maxContentLength: 2000,

  // 定义可获得的http响应状态码
  // return true、设置为null或者undefined,promise将resolved,否则将rejected
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects`定义node.js中要遵循的最大重定向数量。
  // 如果设置为0,则不会执行重定向.
  maxRedirects: 5, // default

  // “httpAgent”和“httpsAgent”定义了在node.js中分别执行https和https请求时使用的自定义代理。 
  // 这允许像“keepAlive”这样添加选项,而这些选项在默认情况下是不启用的。
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // “proxy”定义代理服务器的主机名和端口,用‘false’禁用代理,忽略环境变量。
  // “auth”表示,应该使用HTTP Basic auth连接代理,并提供凭证。
  // 这将设置一个“Proxy-Authorization”头,覆盖您使用“header”设置的任何现有的“Proxy-Authorization”定制头。
  // 代理
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` 指定一个取消令牌,可以用来取消请求
  // (详情见Cancellation 部分)
  cancelToken: new CancelToken(function (cancel) {
  })
}

响应组成

response由以下几部分信息组成

{
  // 服务端返回的数据
  data: {},

  // 服务端返回的状态码
  status: 200,

  // 服务端返回的状态信息
  statusText: 'OK',

  // 响应头
  // 所有的响应头名称都是小写
  headers: {},

  // axios请求配置
  config: {},

  // 请求
  request: {}
}    

then接收以下响应信息

axios.get('/user/12345')
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

当使用catch,或者将 rejection callback作为第二个参数传递时,响应将通过错误对象,如Handling Errors 部分中所解释的那样。

默认配置

全局修改axios默认配置

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

实例默认配置

// 创建实例时修改配置
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 实例创建之后修改配置
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置优先级

配置项通过一定的规则合并,request config > instance.defaults > 系统默认,优先级高的覆盖优先级低的。

// 创建一个实例,这时的超时时间为系统默认的 0
var instance = axios.create();

// 通过instance.defaults重新设置超时时间为2.5s,因为优先级比系统默认高
instance.defaults.timeout = 2500;

// 通过request config重新设置超时时间为5s,因为优先级比instance.defaults和系统默认都高
instance.get('/longRequest', {
  timeout: 5000
});

拦截器

你可以在thencatch之前拦截请求和响应。

// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

如果之后想移除拦截器你可以这么做

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

你也可以为axios实例添加一个拦截器

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

错误处理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 发送请求后,服务端返回的响应码不是 2xx   
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // 发送请求但是没有响应返回
      console.log(error.request);
    } else {
      // 其他错误
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

你可以用validateStatus定义一个http状态码返回的范围.

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; // 只有当状态码大于或等于500时才会拒绝
  }
})

取消请求

你可以通过cancel token来取消一个请求

axios取消令牌API基于撤销的可取消的承诺提案

你可以使用“CancelToken”工厂创建一个取消令牌。如下所示:

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // 处理错误
  }
});

// 取消请求(消息参数是可选的)
source.cancel('Operation canceled by the user.');

您还可以通过将执行器函数传递给CancelToken构造器来创建cancel令牌:

var CancelToken = axios.CancelToken;
var cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // 执行器函数接收一个取消函数作为参数
    cancel = c;
  })
});

// cancel the request
cancel();

注意:您可以用相同的cancel令牌取消多个请求。

使用应用程序/ x-www-form-urlencoded格式

在默认情况下,axios将JavaScript对象序列化为“JSON”。为了将数据发送到“应用程序/x-www-form-urlencode”格式,您可以使用以下选项之一。

浏览器

在浏览器中,你可以用函数URLSearchParamsAPI:

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

请注意,URLSearchParams不受所有浏览器的支持,但是有一个polyfill 可用(确保填充全局环境)。

或者,您可以使用qs库对数据进行编码:

var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

Node.js

在node.js中,你可以使用 querystring 模块:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

你可以使用 qs 库.

版本说明

在axios达到1.0版本之前,重大升级更改将会使用一个新的小版本发布。例如,0.5.1和0.5.4将有相同的API,但是0.6.0将会有重大的变化。

承诺

axios 依赖本地ES6 Promise支持. 如果你的环境不支持 ES6 Promises,你可以使用polyfill.

TypeScript

axios 包含TypeScript 定义.

import axios from 'axios';
axios.get('/user?ID=12345');

参考文献

关于axios

axios的灵感主要来自Angular$http服务 . 最终axios努力实现一个独立的类似$http的 服务.

开源协议

MIT

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.07.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • axios
    • 特性
      • 浏览器支持
        • 安装
          • 例子
            • axios api
              • 请求方法别名
              • 同时发生的请求
              • 创建一个实例
              • 实例的方法
            • 请求配置
              • 响应组成
            • 默认配置
              • 全局修改axios默认配置
              • 实例默认配置
              • 配置优先级
            • 拦截器
              • 错误处理
                • 取消请求
                  • 使用应用程序/ x-www-form-urlencoded格式
                    • 浏览器
                    • Node.js
                  • 版本说明
                    • 承诺
                      • TypeScript
                        • 参考文献
                          • 关于axios
                            • 开源协议
                            领券
                            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档