axios

打印 上一主题 下一主题

主题 565|帖子 565|积分 1695

axios

json-server搭建

https://github.com/typicode/json-server/blob/main/README.md

  • 打开github文档,根据自己的nodejs版本选择json-server的版本。我的nodejs版本为16开头,安装json-server的下令如下:
    1. npm install -g json-server@0.16.3
    复制代码
  • 在文件夹下新建一个db.json文件,将文档中的信息复制进去
    1. {
    2.     "posts": [
    3.       { "id": "1", "title": "a title", "views": 100 },
    4.       { "id": "2", "title": "another title", "views": 200 }
    5.     ],
    6.     "comments": [
    7.       { "id": "1", "text": "a comment about post 1", "postId": "1" },
    8.       { "id": "2", "text": "another comment about post 1", "postId": "1" }
    9.     ],
    10.     "profile": {
    11.       "name": "typicode"
    12.     }
    13.   }
    复制代码
  • 在文件夹下终端中输入下令
    1. json-server --watch db.json
    复制代码
    注意版本差异下令可能会有差异,这里的下令是上面版本的json-server的。这样就启动完成了。
  • 终端会输出三个地点,分别用于访问差异的数据,文档中还有更多的路径对应差异的需求。
axios的先容与页面配置

https://www.axios-http.cn/docs/intro

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

    使用 axios.CancelToken.source() 创建一个取消令牌源,该源对象包罗 token 和 cancel 两个属性:

    • token 用于传递给请求配置以支持取消操作。
    • cancel 是一个函数,可以调用该函数来取消请求。
    1. const cancelTokenSource = axios.CancelToken.source();
    复制代码
    2. 发送请求并附带取消令牌

    在发送请求时,将创建的取消令牌附加到请求配置中:
    1. axios.get('http://localhost:3000/posts', {
    2.   cancelToken: cancelTokenSource.token
    3. })
    4. .then(response => {
    5.   console.log(response.data);
    6. })
    7. .catch(error => {
    8.   if (axios.isCancel(error)) {
    9.     console.log('Request canceled:', error.message);
    10.   } else {
    11.     console.error('Request failed:', error);
    12.   }
    13. });
    复制代码
    3. 取消请求

    在必要取消请求时,调用取消令牌源的 cancel 函数。可以在某个按钮的点击变乱或其他触发条件下实验此操作:
    1. cancelTokenSource.cancel('Request canceled by user.');
    复制代码
    4. 处理取消请求后的响应

    在请求的 .catch 方法中处理取消错误,使用 axios.isCancel(error) 来判断是否由于取消操作引起的错误:
    1. .catch(error => {
    2.   if (axios.isCancel(error)) {
    3.     console.log('Request canceled:', error.message);
    4.   } else {
    5.     console.error('Request failed:', error);
    6.   }
    7. });
    复制代码
    完备代码:

    1. <!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Axios Cancel Request Example</title>    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.2/axios.min.js"></script>    <!-- CSS -->    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.2/css/bootstrap.min.css" rel="stylesheet"        integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"></head><body>    <div class="container">        <h2 class="page-header">axios取消请求</h2>        <button class="btn btn-primary" id="send-request">发送请求</button>        <button class="btn btn-warning" id="cancel-request">取消请求</button>    </div>    <script>        let cancelTokenSource;        document.getElementById('send-request').onclick = function() {            // 假如之前有未完成的请求,则取消它            if (cancelTokenSource) {                cancelTokenSource.cancel('Operation canceled by the user.');            }            // 创建新的取消令牌            cancelTokenSource = axios.CancelToken.source();            axios.get('http://localhost:3000/posts', {                cancelToken: cancelTokenSource.token            })            .then(response => {                console.log(response.data);                cancelTokenSource = null; // 请求完成后清除取消令牌            })            .catch(error => {                if (axios.isCancel(error)) {                    console.log('Request canceled:', error.message);                } else {                    console.error('Request failed:', error);                }                cancelTokenSource = null; // 请求失败后清除取消令牌            });        };        document.getElementById('cancel-request').onclick = function() {            if (cancelTokenSource) {                cancelTokenSource.cancel('Request canceled by user.');
    2.                 console.log('请求已取消');            } else {                console.log('没有正在举行的请求');            }        };    </script></body></html>
    复制代码
    步调总结

       

    • 创建取消令牌:使用 axios.CancelToken.source() 创建。
    • 发送请求并附带取消令牌:将 cancelTokenSource.token 添加到请求配置中。
    • 取消请求:调用 cancelTokenSource.cancel('取消原因')。
    • 处理取消后的响应:在 .catch 方法中使用 axios.isCancel(error) 判断是否为取消请求导致的错误。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

三尺非寒

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表