解决AbortController中断请求无法再次请求

示例代码

express代码

javascript 复制代码
const express = require('express')
const app = express()

//导入cors跨域中间件
const cors = require('cors')
// 全局注册,加前缀
app.use(cors())

app.get('/list', (req, res) => {
  // 直接返回对象
  console.log('接收到的参数是', req.query)
  //结束本次请求,设置响应体:返回给用户内容
  setTimeout(() => {
    res.send({ message: 'success', code: 2000, data: [{ name: '张三', age: 18 }] })
  }, 4000)
})

app.post('/data', (req, res) => {
  setTimeout(() => {
    res.send({ message: 'success', code: 2000, data: [{ name: '张三666', age: 18 }] })
  }, 4000)
})

app.listen('3000', () => {
  console.log('服务启动成功')
})

html代码

javascript 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button onclick="sendGet()">get请求</button>
    <button onclick="sendPost()">post请求</button>
    <button onclick="cancel()">取消</button>
  </body>

  <script>
  	// 初始化 controller 为 null,用来处理中止请求后无法再次发请求
    let controller = null
    if (!controller) {
      function sendGet() {
        controller = new AbortController()
        fetch('http://localhost:3000/list?name=haha&age=19', {
          signal: controller.signal
        })
          .then((res) => {
            if (res.ok) {
              return res.json()
            }
          })
          .catch((err) => {
            console.log(err)
          })
      }
      function sendPost() {
        controller = new AbortController()
        fetch('http://localhost:3000/data', {
          method: 'POST',
          body: JSON.stringify(),
          headers: {
            'Content-Type': 'application/json'
          },
          signal: controller.signal
        }).then((res) => {
          console.log(res)
        })
      }
    }
    function cancel() {
      controller.abort() // 取消请求
      controller = ''
    }
  </script>
</html>
相关推荐
@大迁世界7 小时前
Firefox 本地模式:localhost 再见了 ?
前端·架构
米米商聊9 小时前
同名附件为什么被 Map 覆盖?重复键与一对多索引
前端·javascript
echome88810 小时前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
时间的情敌10 小时前
OpenLayers 实战|Vue3 + OpenLayers 完整工程案例(加载天地图、要素、弹窗、绘制、WFS)
前端·openlayers
陈随易10 小时前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
前端的日常10 小时前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师11 小时前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么11 小时前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析
IT_陈寒11 小时前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端
hunter_07611 小时前
一次 iOS 真机签名 409 的完整排查:证书、设备、描述文件为什么总是"对不上"
前端