1.代码示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script> </head> <body> <div class="container"> <h2 class="page-header">基本使用</h2> <button class="btn btn-primary"> 发送GET请求 </button> <button class="btn btn-warning"> 发送POST请求 </button> </div> <script> const btns = document.querySelectorAll("button"); let cancel = null; btns[0].onclick = function() { axios({ method: "GET", url: "http://localhost:3000/posts", cancelToken: new axios.CancelToken(function(c) { cancel = c; }) }).then(response => { console.log(response); }) }, btns[1].onclick = function() { cancel(); } </script> </body> </html>
2.让服务器延长响应时间方法:
json-server --watch db.json --Delay 2000(在这里写入要规定的响应时间)
或者
json-server --watch db.json -d 2000(在这里写入要规定的响应时间)
3.检测上次请求是否完成(或者说限制客户端只能向服务器发送一次请求)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script> </head> <body> <div class="container"> <h2 class="page-header">基本使用</h2> <button class="btn btn-primary"> 发送GET请求 </button> <button class="btn btn-warning"> 发送POST请求 </button> </div> <script> const btns = document.querySelectorAll("button"); let cancel = null; btns[0].onclick = function() { if (cancel != null) { cancel(); } axios({ method: "GET", url: "http://localhost:3000/posts", cancelToken: new axios.CancelToken(function(c) { cancel = c; }) }).then(response => { console.log(response); cancel = null; }) }, btns[1].onclick = function() { cancel(); } </script> </body> </html>