前置代码,先起一个简单的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>