js/vue3 取消已发送网络请求的方式

11 篇文章 2 订阅

前置代码,先起一个简单的node本地服务,代码如下:

/*
 * @Author: muge
 * @Date: 2022-06-16 15:27:11
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-06-23 09:59:43
 */
//导入express
const express = require("express");
//调用express得到app
const app = express();
app.all("*", function (req, res, next) {
  //设置允许跨域的域名,*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", "*");
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "*");
  //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "*");
  if (req.method.toLowerCase() == "options") res.send(200);
  //让options尝试请求快速结束
  else next();
});
app.get("/", (req, res) => {
  console.log("接收了");
  setTimeout(() => res.send("发送了数据"), 2500);
});
//监听端口号,启动 Web 服务
app.listen(3005, () => {
  console.log("服务器启动成功,请在http://localhost:3005中访问....");
});
//自动 node index.js  或者安装nodemon =>nodemon index.js

一、xmlhttprequest

官方解释:XMLHttpRequest.abort()如果请求已经发送, 该方法将中止请求。当一个请求被中止时,它 readyState被更改为 XMLHttpRequest.UNSENT(0) 并且请求的 status代码被设置为 0。

<script setup>
	const xhr = new XMLHttpRequest();
	import {
		ref
	} from 'vue'

	defineProps({
		msg: String
	})
	const send = () => {
		xhr.open('GET', 'http://localhost:3005/', true);
		xhr.send();
	}
	const cancle = () => {
		xhr.abort();
	}
</script>

<template>
	<button @click="send">发送</button>
	<button @click="cancle">取消</button>
</template>

<style scoped>

</style>

在这里插入图片描述

二、fetch

AbortController 接口表示一个控制器对象,允许你根据需要中止一个或多个 Web 请求。

你可以使用 AbortController.AbortController() 构造函数创建一个新的 AbortController。使用 AbortSignal 对象可以完成与 DOM 请求的通信。

<script setup>
	const controller = new AbortController();
	import {
		ref
	} from 'vue'

	defineProps({
		msg: String
	})
	const send = () => {
		fetch('http://localhost:3005', {
			signal: controller.signal,
		});
	}
	const cancle = () => {
		controller.abort();
	}
</script>

<template>
	<button @click="send">发送</button>
	<button @click="cancle">取消</button>
</template>

<style scoped>

</style>

效果如上图,就不放了

三、axios

实现跟fetch一样的

<script setup>
	import axios from 'axios'
	const controller = new AbortController();
	import {
		ref
	} from 'vue'

	defineProps({
		msg: String
	})
	const send = () => {
		 axios.get('http://localhost:3005', {
			signal: controller.signal,
		});
	}
	const cancle = () => {
		controller.abort();
	}
</script>

<template>
	<button @click="send">发送</button>
	<button @click="cancle">取消</button>
</template>

<style scoped>

</style>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值