• axios 基本使用与学习


    官网

    Axios 中文文档 | Axios 中文网 | Axios 是一个基于 promise 的网络请求库,可以用于浏览器和 node.js

     Axios 是什么?

    Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。

    特性

    • 从浏览器创建 XMLHttpRequests
    • 从 node.js 创建 http 请求
    • 支持 Promise API
    • 拦截请求和响应
    • 转换请求和响应数据
    • 取消请求
    • 自动转换JSON数据
    • 客户端支持防御XSRF

    安装

    使用 npm:

    npm install axios

    使用 bower:

    bower install axios

    使用 yarn:

    yarn add axios

    使用 jsDelivr CDN:

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js">script>

     

    使用 unpkg CDN:

    <script src="https://unpkg.com/axios/dist/axios.min.js">script>

    基本用例

    注意: CommonJS 用法

    为了在CommonJS中使用 require() 导入时获得TypeScript类型推断(智能感知/自动完成),请使用以下方法

    1. const axios = require('axios').default;
    2. // axios. 能够提供自动完成和参数类型推断功能

    用例

    发起一个 GET 请求

    1. const axios = require('axios');
    2. // 向给定ID的用户发起请求
    3. axios.get('/user?ID=12345')
    4. .then(function (response) {
    5. // 处理成功情况
    6. console.log(response);
    7. })
    8. .catch(function (error) {
    9. // 处理错误情况
    10. console.log(error);
    11. })
    12. .then(function () {
    13. // 总是会执行
    14. });
    15. // 上述请求也可以按以下方式完成(可选)
    16. axios.get('/user', {
    17. params: {
    18. ID: 12345
    19. }
    20. })
    21. .then(function (response) {
    22. console.log(response);
    23. })
    24. .catch(function (error) {
    25. console.log(error);
    26. })
    27. .then(function () {
    28. // 总是会执行
    29. });
    30. // 支持async/await用法
    31. async function getUser() {
    32. try {
    33. const response = await axios.get('/user?ID=12345');
    34. console.log(response);
    35. } catch (error) {
    36. console.error(error);
    37. }
    38. }

    用Axios如何发起POST请求

    发起一个 POST 请求

    1. axios.post('/user', {
    2. firstName: 'Fred',
    3. lastName: 'Flintstone'
    4. })
    5. .then(function (response) {
    6. console.log(response);
    7. })
    8. .catch(function (error) {
    9. console.log(error);
    10. });

    发起多个并发请求

    1. function getUserAccount() {
    2. return axios.get('/user/12345');
    3. }
    4. function getUserPermissions() {
    5. return axios.get('/user/12345/permissions');
    6. }
    7. Promise.all([getUserAccount(), getUserPermissions()])
    8. .then(function (results) {
    9. const acct = results[0];
    10. const perm = results[1];
    11. });

    Axios API

    可以向 axios 传递相关配置来创建请求

    axios(config)

    1. // 发起一个post请求
    2. axios({
    3. method: 'post',
    4. url: '/user/12345',
    5. data: {
    6. firstName: 'Fred',
    7. lastName: 'Flintstone'
    8. }
    9. });

    1. // 在 node.js 用GET请求获取远程图片
    2. axios({
    3. method: 'get',
    4. url: 'http://bit.ly/2mTM3nY',
    5. responseType: 'stream'
    6. })
    7. .then(function (response) {
    8. response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
    9. });

    axios(url[, config])

    1. // 发起一个 GET 请求 (默认请求方式)
    2. 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 这些属性都不必在配置中指定

    Axios 实例

    创建一个实例

    您可以使用自定义配置新建一个实例。

    axios.create([config])

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

    实例方法

    以下是可用的实例方法。指定的配置将与实例的配置合并。

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

    请求配置

    1. {
    2. // `url` 是用于请求的服务器 URL
    3. url: '/user',
    4. // `method` 是创建请求时使用的方法
    5. method: 'get', // 默认值
    6. // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
    7. // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
    8. baseURL: 'https://some-domain.com/api/',
    9. // `transformRequest` 允许在向服务器发送前,修改请求数据
    10. // 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
    11. // 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
    12. // 你可以修改请求头。
    13. transformRequest: [function (data, headers) {
    14. // 对发送的 data 进行任意转换处理
    15. return data;
    16. }],
    17. // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
    18. transformResponse: [function (data) {
    19. // 对接收的 data 进行任意转换处理
    20. return data;
    21. }],
    22. // 自定义请求头
    23. headers: {'X-Requested-With': 'XMLHttpRequest'},
    24. // `params` 是与请求一起发送的 URL 参数
    25. // 必须是一个简单对象或 URLSearchParams 对象
    26. params: {
    27. ID: 12345
    28. },
    29. // `paramsSerializer`是可选方法,主要用于序列化`params`
    30. // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
    31. paramsSerializer: function (params) {
    32. return Qs.stringify(params, {arrayFormat: 'brackets'})
    33. },
    34. // `data` 是作为请求体被发送的数据
    35. // 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
    36. // 在没有设置 `transformRequest` 时,则必须是以下类型之一:
    37. // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
    38. // - 浏览器专属: FormData, File, Blob
    39. // - Node 专属: Stream, Buffer
    40. data: {
    41. firstName: 'Fred'
    42. },
    43. // 发送请求体数据的可选语法
    44. // 请求方式 post
    45. // 只有 value 会被发送,key 则不会
    46. data: 'Country=Brasil&City=Belo Horizonte',
    47. // `timeout` 指定请求超时的毫秒数。
    48. // 如果请求时间超过 `timeout` 的值,则请求会被中断
    49. timeout: 1000, // 默认值是 `0` (永不超时)
    50. // `withCredentials` 表示跨域请求时是否需要使用凭证
    51. withCredentials: false, // default
    52. // `adapter` 允许自定义处理请求,这使测试更加容易。
    53. // 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
    54. adapter: function (config) {
    55. /* ... */
    56. },
    57. // `auth` HTTP Basic Auth
    58. auth: {
    59. username: 'janedoe',
    60. password: 's00pers3cret'
    61. },
    62. // `responseType` 表示浏览器将要响应的数据类型
    63. // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
    64. // 浏览器专属:'blob'
    65. responseType: 'json', // 默认值
    66. // `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
    67. // 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
    68. // Note: Ignored for `responseType` of 'stream' or client-side requests
    69. responseEncoding: 'utf8', // 默认值
    70. // `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
    71. xsrfCookieName: 'XSRF-TOKEN', // 默认值
    72. // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
    73. xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
    74. // `onUploadProgress` 允许为上传处理进度事件
    75. // 浏览器专属
    76. onUploadProgress: function (progressEvent) {
    77. // 处理原生进度事件
    78. },
    79. // `onDownloadProgress` 允许为下载处理进度事件
    80. // 浏览器专属
    81. onDownloadProgress: function (progressEvent) {
    82. // 处理原生进度事件
    83. },
    84. // `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
    85. maxContentLength: 2000,
    86. // `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
    87. maxBodyLength: 2000,
    88. // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
    89. // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
    90. // 则promise 将会 resolved,否则是 rejected。
    91. validateStatus: function (status) {
    92. return status >= 200 && status < 300; // 默认值
    93. },
    94. // `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
    95. // 如果设置为0,则不会进行重定向
    96. maxRedirects: 5, // 默认值
    97. // `socketPath` 定义了在node.js中使用的UNIX套接字。
    98. // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
    99. // 只能指定 `socketPath` 或 `proxy` 。
    100. // 若都指定,这使用 `socketPath` 。
    101. socketPath: null, // default
    102. // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
    103. // and https requests, respectively, in node.js. This allows options to be added like
    104. // `keepAlive` that are not enabled by default.
    105. httpAgent: new http.Agent({ keepAlive: true }),
    106. httpsAgent: new https.Agent({ keepAlive: true }),
    107. // `proxy` 定义了代理服务器的主机名,端口和协议。
    108. // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
    109. // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
    110. // `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
    111. // 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
    112. // 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
    113. proxy: {
    114. protocol: 'https',
    115. host: '127.0.0.1',
    116. port: 9000,
    117. auth: {
    118. username: 'mikeymike',
    119. password: 'rapunz3l'
    120. }
    121. },
    122. // see https://axios-http.com/zh/docs/cancellation
    123. cancelToken: new CancelToken(function (cancel) {
    124. }),
    125. // `decompress` indicates whether or not the response body should be decompressed
    126. // automatically. If set to `true` will also remove the 'content-encoding' header
    127. // from the responses objects of all decompressed responses
    128. // - Node only (XHR cannot turn off decompression)
    129. decompress: true // 默认值
    130. }

    响应结构

    1. {
    2. // `data` 由服务器提供的响应
    3. data: {},
    4. // `status` 来自服务器响应的 HTTP 状态码
    5. status: 200,
    6. // `statusText` 来自服务器响应的 HTTP 状态信息
    7. statusText: 'OK',
    8. // `headers` 是服务器响应头
    9. // 所有的 header 名称都是小写,而且可以使用方括号语法访问
    10. // 例如: `response.headers['content-type']`
    11. headers: {},
    12. // `config``axios` 请求的配置信息
    13. config: {},
    14. // `request` 是生成此响应的请求
    15. // 在node.js中它是最后一个ClientRequest实例 (in redirects),
    16. // 在浏览器中则是 XMLHttpRequest 实例
    17. request: {}
    18. }

    当使用 then 时,您将接收如下响应:

    1. axios.get('/user/12345')
    2. .then(function (response) {
    3. console.log(response.data);
    4. console.log(response.status);
    5. console.log(response.statusText);
    6. console.log(response.headers);
    7. console.log(response.config);
    8. });

    默认配置

    您可以指定默认配置,它将作用于每个请求。

    全局 axios 默认值

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

    自定义实例默认值

    1. // 创建实例时配置默认值
    2. const instance = axios.create({
    3. baseURL: 'https://api.example.com'
    4. });
    5. // 创建实例后修改默认值
    6. instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

    配置的优先级

    配置将会按优先级进行合并。它的顺序是:在lib/defaults.js中找到的库默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后面的优先级要高于前面的。下面有一个例子。

    1. // 使用库提供的默认配置创建实例
    2. // 此时超时配置的默认值是 `0`
    3. const instance = axios.create();
    4. // 重写库的超时默认值
    5. // 现在,所有使用此实例的请求都将等待2.5秒,然后才会超时
    6. instance.defaults.timeout = 2500;
    7. // 重写此请求的超时时间,因为该请求需要很长时间
    8. instance.get('/longRequest', {
    9. timeout: 5000
    10. });

    拦截器

    在请求或响应被 then 或 catch 处理前拦截它们。

    1. // 添加请求拦截器
    2. axios.interceptors.request.use(function (config) {
    3. // 在发送请求之前做些什么
    4. return config;
    5. }, function (error) {
    6. // 对请求错误做些什么
    7. return Promise.reject(error);
    8. });
    9. // 添加响应拦截器
    10. axios.interceptors.response.use(function (response) {
    11. // 2xx 范围内的状态码都会触发该函数。
    12. // 对响应数据做点什么
    13. return response;
    14. }, function (error) {
    15. // 超出 2xx 范围的状态码都会触发该函数。
    16. // 对响应错误做点什么
    17. return Promise.reject(error);
    18. });

     

    如果你稍后需要移除拦截器,可以这样:

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

     

    可以给自定义的 axios 实例添加拦截器

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

    错误处理

    1. axios.get('/user/12345')
    2. .catch(function (error) {
    3. if (error.response) {
    4. // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
    5. console.log(error.response.data);
    6. console.log(error.response.status);
    7. console.log(error.response.headers);
    8. } else if (error.request) {
    9. // 请求已经成功发起,但没有收到响应
    10. // `error.request` 在浏览器中是 XMLHttpRequest 的实例,
    11. // 而在node.js中是 http.ClientRequest 的实例
    12. console.log(error.request);
    13. } else {
    14. // 发送请求时出了点问题
    15. console.log('Error', error.message);
    16. }
    17. console.log(error.config);
    18. });

    使用 validateStatus 配置选项,可以自定义抛出错误的 HTTP code

    1. axios.get('/user/12345', {
    2. validateStatus: function (status) {
    3. return status < 500; // 处理状态码小于500的情况
    4. }
    5. })

    使用 toJSON 可以获取更多关于HTTP错误的信息。

    1. axios.get('/user/12345')
    2. .catch(function (error) {
    3. console.log(error.toJSON());
    4. });

    取消请求

    AbortController

    从 v0.22.0 开始,Axios 支持以 fetch API 方式—— AbortController 取消请求:

    1. const controller = new AbortController();
    2. axios.get('/foo/bar', {
    3. signal: controller.signal
    4. }).then(function(response) {
    5. //...
    6. });
    7. // 取消请求
    8. controller.abort()

    请求体编码

    默认情况下,axios将 JavaScript 对象序列化为 JSON 。 要以application/x-www-form-urlencoded格式发送数据,您可以使用以下选项之一。

    浏览器

    在浏览器中,可以使用URLSearchParams API,如下所示:

    1. const params = new URLSearchParams();
    2. params.append('param1', 'value1');
    3. params.append('param2', 'value2');
    4. axios.post('/foo', params);

    请注意,不是所有的浏览器(参见 caniuse.com)都支持 URLSearchParams ,但是可以使用polyfill (确保 polyfill 全局环境)

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

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

    或者用另一种方式 (ES6)

    1. import qs from 'qs';
    2. const data = { 'bar': 123 };
    3. const options = {
    4. method: 'POST',
    5. headers: { 'content-type': 'application/x-www-form-urlencoded' },
    6. data: qs.stringify(data),
    7. url,
    8. };
    9. axios(options);

    Form data

    在 node.js, 您可以使用 form-data 库,如下所示:

    1. const FormData = require('form-data');
    2. const form = new FormData();
    3. form.append('my_field', 'my value');
    4. form.append('my_buffer', new Buffer(10));
    5. form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
    6. axios.post('https://example.com', form, { headers: form.getHeaders() })

    或者, 使用一个拦截器:

    1. axios.interceptors.request.use(config => {
    2. if (config.data instanceof FormData) {
    3. Object.assign(config.headers, config.data.getHeaders());
    4. }
    5. return config;
    6. });

  • 相关阅读:
    Pytorch安装20221029
    深入理解 Swift 新并发模型中 Actor 的重入(Reentrancy)问题
    JAVA直播购物平台计算机毕业设计Mybatis+系统+数据库+调试部署
    [java] 23种设计模式之代理模式
    神辅助 Cursor 编辑器,加入 GPT-4 让编码更轻松!
    基于RK3568的内部定时器应用示例
    2024华为校招面试真题汇总及其解答(二)
    MySql 数据库初始化,创建用户,创建数据库,授权
    EraseNet:End-to-End Text Removal in the wild
    如何系统的去学c#
  • 原文地址:https://blog.csdn.net/weixin_53657413/article/details/126085963