解决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>
相关推荐
浪裡遊8 分钟前
MUI组件库与主题系统全面指南
开发语言·前端·javascript·vue.js·react.js·前端框架·node.js
DiXinWang31 分钟前
关闭谷歌浏览器提示“若要接收后续 Google Chrome 更新,您需使用 Windows 10 或更高版本”的方法
前端·chrome
CoderYanger39 分钟前
前端基础——HTML练习项目:填写简历信息
前端·css·职场和发展·html
muyouking1144 分钟前
深入理解 HTML `<label>` 的 `for` 属性:提升表单可访问性与用户体验
前端·html·ux
IT_陈寒1 小时前
Java性能调优:从GC日志分析到实战优化的5个关键技巧,让你的应用快如闪电!
前端·人工智能·后端
Mintopia1 小时前
🚀 Next.js API 压力测试:一场前端与后端的“极限拉扯”
前端·后端·全栈
Mintopia1 小时前
🛡️ 对抗性攻击与防御:WebAI模型的安全加固技术
前端·javascript·aigc
庙堂龙吟奈我何1 小时前
qiankun知识点
前端
SoaringHeart2 小时前
Flutter封装:原生路由管理极简封装 AppNavigator
前端·flutter
menu2 小时前
AI给我的建议
前端