本文翻译自 axios 的 github 说明文档

axios

概述

axios 是一个基于 promise 的 HTTP 库, 可以用在浏览器和 node.js 中

例子

注意: CommonJS 方式

在使用 CommonJS 用 require() 导入是, 为了使用 TypeScript 中的强类型的方式(为了智能补全), 使用如下的方法:

const axios = require('axios').default;

// axios.<method> 下载用这种方式将会拥有智能补全和强类型的参数的优点

发起一个 GET 请求

const axios = require('axios');

// 请求一个拥有特定 ID 的用户信息
axios.get('/user?ID=12345')
  .then(function (response) {
    // 成功的 handler
    console.log(response);
  })
  .catch(function (error) {
    // 错误的 handler
    console.log(error);
  })
  .finally(function () {
    // 总会执行
  });

// 您也可以选择如下的方式
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // 总会执行
  });  

// 想使用 async/await ? 没问题, 添加一个 async 关键字到你外层的函数前面
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

注意: async/await 是 ECMAScript2017 中的一部分, 它不支持 IE 浏览器和更早期的浏览器, 请谨慎使用

发起一个 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) {
    // 此时, 所有的请求都已完成
  }));

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, method, 和 data 属性不需要在配置对象 (config) 中特殊指明

同时进行的方法

以下是处理同时进行多个请求的情况时可用的方法

axios.all(iterable)

axios.spread(callback)

创建一个实例

可以使用一个 config 对象创建一个 axios 实例

axios.create([config])

const instance = axios.create({
    baseURL: 'https://some-doman.com/api',
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
});

实例方法

可供实例使用的方法如下. 方法中特化的 config 会与创建实例时的 config 合并

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]])

axios#getUri([config])

请求 config

发起请求时, 有以下选项供配置, 其中只有 url 是必须的. 如果 method 没有使用, 默认会使用 GET 方法.

{
  // 请求的 url
  url: '/user',

  // 发起请求的方法
  method: 'get', // 默认为 GET

  // baseURL 一般会前置填充到 url上, 除非 url 本身就是绝对路径
  // 给axios实例设置 baseURL 会简化请求相关url
  baseURL: 'https://some-domain.com/api/',

  // 此属性允许您在请求数据发送到服务器之前改变它.
  // 只适用于部分请求方法: PUT, POST, PATCH, DELETE.
  // 数组中的最后一个方法必须要返回一个 字符串 或者 一个 Buffer或ArrayBuffer或FormData或Stream的实例.
  // 您可以在此修改 headers 对象
  transformRequest: [function (data, headers) {
    // 在此您可以任意修改请求数据

    return data;
  }],

  // 此属性允许您在响应数据传递到 then/catch 之前修改数据
  transformResponse: [function (data) {
    // 在此您可以任意修改响应数据

    return data;
  }],

  // 自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // 此字段包含了请求携带的 URL参数.
  // 必须是 扁平对象 或者 URLSearchParams对象.
  params: {
    ID: 12345
  },

  // 这是个可选函数, 用于序列化 params
  // (比如  https://www.npmjs.com/package/qs , http://api.jquery.com/jquery.param/)
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },
  
  // data字段内容将作为请求体发送.
  // 只有当方法是 PUT, POST, PATCH 时有效.
  // 当 transformRequest 字段没有设置时, 此字段内容只能是一下几种类型:
  // - 字符串, 扁平化对象, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 只适用于服务器端: FormData, File, Blob
  // - 只适用于Node段: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
  
  // 另一种可选的请求体数据语法
  // 方法: post
  // 只传递值, 不传递键 ??
  data: 'Country=Brasil&City=Belo Horizonte',

  // 请求超时的毫秒数.
  // 如果发送请求超过了 timeout 设置的时间, 请求将会终止(流产)
  timeout: 1000, // 默认值为0 (即不设置timeout)

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  // 此字段指明跨站且有访问控制的请求需不需要使用证书
  withCredentials: false, // 默认值

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  // adapter: 适配器
  // 允许自定义处理请求, 将会简化测试
  // 返回一个 promise 且提供一个有效的响应(更多请参考 lib/adapters/README.md)
  adapter: function (config) {
    /* ... */
  },
  
  // `auth` 字段指明应该使用 HTTP 基本认证, 且需要提供证书
  // 使用这个字段时, 会在 headers 中设置一个 `Authorization` 字段, 并且会覆盖掉您使用 headers 设置的自定义头部信息.
  // 请注意: 此参数只能配置 HTTP 基本认证.
  // 当使用 Bearer tokens 或其他的认证方式时, 请使用自定义头部字段 `Authorization`.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // 此字段指明了服务器应该响应的数据类型.
  // 可选参数: arraybuffer, document, json, text, stream
  // 只适用于浏览器: blob (binary large object, 二进制大对象, 是一个可以存储二进制文件的容器)
  responseType: 'json', // default

  // 解码响应内容的格式.
  // 当使用 stream 类型的数据作为响应类型或者客户端请求时此选项会被忽略.
  responseEncoding: 'utf8', // default

  // xsrf: cross site request forgeries 跨域请求伪造
  // cookie 的名字将作为 xsrf token 的值
  xsrfCookieName: 'XSRF-TOKEN', // default

  // http header 中携带 xsrf token 值的名字
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` allows handling of progress events for uploads
  // 此字段允许我们处理上传中的 progress 事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
    // 尽情应用原生的 progress 事件
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // http 响应内容的最大长度(byte)
  maxContentLength: 2000,

  // validateStatus 决定我们如何对于一个 HTTP 响应状态码来 resolve 或 reject 一个 promise.
  // 如果返回 true, resolve
  // 如果返回 false, reject
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  // maxRedirects 决定在 nodejs 中的可以紧跟重定向的最大次数.
  // 如果次数为0, 不允许紧跟的重定向.
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  // socketPath 定义了一个nodejs中使用的 UNIX Socket.
  // 比如: '/var/run/docker.sock' 向 docker 后台(docker daemon)发送请求.
  // socketPath 和 proxy 只能使用一个
  // 如果使用了上述中的两个, 那么最终会使用 socketPath
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  // httpAgent 和 httpsAgent 属性定义了nodejs中, 当使用 http 和 https 时的自定义代理
  // 同时可以添加 keepAlive 一类的默认不开启的设置.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the hostname and port of the proxy server.
  // You can also define your proxy using the conventional `http_proxy` and
  // `https_proxy` environment variables. If you are using environment variables
  // for your proxy configuration, you can also define a `no_proxy` environment
  // variable as a comma-separated list of domains that should not be proxied.
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  // proxy 定义了代理服务器的 主机名字 和 端口
  // 也可以使用常用的环境变量 http_proxy 和 https_proxy 来定义代理. 使用环境变量配置代理服务器时, 也可以定义一个 no_proxy 环境变量, 值为以 ','分隔的不应该被代理的域的列表.
  // 值设置为 false 时, 禁止代理, 忽略环境变量的设置.
  // `auth` 字段指明连接到代理服务器时,应该使用 HTTP 基本认证, 且需要提供证书.
  // 使用这个字段时, 同上, 会在 headers 中设置一个 `Proxy-Authorization` 字段, 并且会覆盖掉您使用 headers 设置的自定义头部信息.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  // cancelToken 指明一个 cancel token, 用于取消请求.
  // 了解关于 Cancellation 请看下文.
  cancelToken: new CancelToken(function (cancel) {
  })
}

响应概要

一个请求的响应包含了如下的信息.

{
  // `data` is the response that was provided by the server
  // data 是服务器提供的响应
  data: {},

  // `status` is the HTTP status code from the server response
  // 服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` is the HTTP status message from the server response
  // 服务器响应的 HTTP 状态信息
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  // 服务器响应的 headers
  // 所有的 header 名字都是小写的
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  // config 是 请求时提供给 axios 的 config
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  // request 是产生这个响应的 request
  // 在nodejs中, 它是最后一个 客户端请求实例 (ClientRequest instance)(在重定向中);
  // 在浏览器中, 它是一个 XMLHttpRequest 实例.
  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 或者 传递一个 reject的回调 作为 then 的第二个参数时, 响应会通过错误对象的形式传递(如前面处理错误章节所描述)

配置默认项

您可以特殊配置每个request的配置项的默认值.

全局 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';

自定义实例的默认项配置:

// Set config defaults when creating the instance
// 创建实例的同时配置默认项
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
// 实例创建后更改默认项
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置的优先级顺序

配置项会按照一个优先级的顺序进行合并.顺序如lib/defaults所列(The order is library defaults found in lib/defaults.js,),然后是实例的 defaults 属性,最后是请求的 config 参数。后者会覆盖前者,例子如下:

// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
// 使用 library 提供的 config defaults 创建实例
// 在这个时间点 timeout 配置项的值为 0,也是 library 的默认值。
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
// 覆写 library 的超时数值
// 此时,所有使用此实例的请求都会在超时前等待 2.5 秒
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
// 当已知此次请求会花很长时间时,覆写请求的超时时长
instance.get('/longRequest', {
  timeout: 5000
});
 posted on 2019-10-22 15:01  JiaoPi  阅读(552)  评论(0)    收藏  举报