解决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>
相关推荐
卡兰芙的微笑19 分钟前
get_property --Cmakelist之中
前端·数据库·编辑器
覆水难收呀22 分钟前
三、(JS)JS中常见的表单事件
开发语言·前端·javascript
猿来如此呀29 分钟前
运行npm install 时,卡在sill idealTree buildDeps没有反应
前端·npm·node.js
hw_happy35 分钟前
解决 npm ERR! node-sass 和 gyp ERR! node-gyp 报错问题
前端·npm·sass
FHKHH39 分钟前
计算机网络第二章:作业 1: Web 服务器
服务器·前端·计算机网络
视觉小鸟1 小时前
【JVM安装MinIO】
前端·jvm·chrome
二川bro2 小时前
【已解决】Uncaught RangeError: Maximum depth reached
前端
qq22951165023 小时前
python毕业设计基于django+vue医院社区医疗挂号预约综合管理系统7918h-pycharm-flask
前端·vue.js·express
八了个戒3 小时前
Koa (下一代web框架) 【Node.js进阶】
前端·node.js
Sca_杰3 小时前
vue2使用npm引入依赖(例如axios),报错Module parse failed: Unexpected token解决方案
前端·javascript·vue