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>
<script src="https://unpkg.com/lodash@4.17.21/lodash.js"></script>
</head>
<body>
<div id="app">
<button @click="fetchInfo">获取网络数据</button>
<button @click="cancel">取消</button>
</div>
</body>
<script>
let fetchBtn = document.querySelector("button:first-of-type")
let cancelBtn = document.querySelector("button:last-of-type")
let controller;
let url='http://localhost:7002';//一个需要三秒响应的后台服务
//使用防抖技术,一秒钟内只能发送一次请求
let reqFn=_.debounce((event) => {
//每一次请求对应一个controller,其signal状态一旦变成aborted,将不可逆转,不能再次发送网络请求
//如果请求未被取消,则首先取消上次的请求
if(controller&&!controller.signal.aborted){
controller.abort();
}
controller= new AbortController();
fetch(url,{ signal:controller.signal }).then(resp => resp.text())
.then(info => {
console.log(info)
})
.catch(error => {
console.log(error)
})
},1000);
fetchBtn.addEventListener("click", reqFn)
cancelBtn.addEventListener('click',()=>{
if(!controller.signal.aborted){
controller.abort();
console.log('请求被终止。。');
}
})
</script>
</html>
2. 附录,后端egg.js代码:
安装egg-cors插件:
npm install egg-cors
config/plugin.js
'use strict';
/** @type Egg.EggPlugin */
exports.cors = {
enable: true,
package: 'egg-cors',
};
config/config.default.js:
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1661496302119_191';
// add your middleware config here
config.middleware = [];
config.security = {
csrf: {
enable: false,
ignoreJSON: true
},
domainWhiteList: ['http://localhost:8080']
};
config.cors = {
origin:'*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
};
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
controller/home.js
'use strict';
const Controller = require('egg').Controller;
function fn(){
return new Promise((resolv,reject)=>{
setTimeout(()=>{
resolv("johnyu"+Math.random())
},2000)
})
}
class HomeController extends Controller {
async index() {
const { ctx } = this;
//一个延迟3秒的异步访问
const info=await fn()
ctx.set('Content-Type','application/json')
let obj={id:1,name:info}
ctx.body = obj;
}
}
module.exports = HomeController;
网友评论