解决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>
相关推荐
Bigger1 小时前
Tauri (26)——托盘图标总对不上系统主题?一行 Template Image 搞定
前端·rust·app
kyriewen4 小时前
面试官问你:“AI 能写 80% 的代码了,公司为什么还需要你?”
前端·javascript·面试
甲维斯4 小时前
又升级咯!坦克大战2026,科技与复古并存!
前端·人工智能·游戏开发
搬砖的码农7 小时前
(08)为什么我的 Agent 一跑后台服务就卡死
前端·agent·ai编程
飘尘7 小时前
前端转全栈(Java 后端)必须要知道的:开发中的锁机制与分布式并发控制
前端·后端·全栈
亲亲小宝宝鸭7 小时前
前端性能监控:web-vitals
前端·性能优化·监控
陆枫Larry7 小时前
可滚动页面背景填不满:`height: 100vh` vs `min-height: 100vh`
前端
Patrick_Wilson7 小时前
Squash Merge 的血缘陷阱:为什么删掉的代码又活了过来
前端·git·程序员
kyriewen8 小时前
今天的科技圈,全在抢英伟达的饭碗
前端·面试·ai编程