ajax的响应与取消响应

第一部分:axios取消响应 

1.使用 CancelToken.source 工厂方法创建cancel token

CancelToken有一个source静态方法,调用之后返回一个对象,该对象包含一个token属性用于标

记请求和一个cancel方法用于取消请求

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<body>
   <button type="button">点我</button>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
   let btn =  document.querySelector('button')

   const CancelToken = axios.CancelToken;
   const source = CancelToken.source();

   btn.addEventListener('click',function(){
       const CancelToken = axios.CancelToken;
       const source = CancelToken.source();
       axios({
           url:'http://localhost:3000/',
           method:'get',
           params: {age:"18"},
           //标记请求
           cancelToken: source.token
       }).then(res=>{
           //成功回调
           console.log(res)
            
       })
       // 当请求发送时,在2s内没有接受到响应,则响应取消
       setTimeout(()=>{
           source.cancel('不想请求了');
       },2000)
        
   })
</script>
</html>

第二部分:ajax取消请求

xhr.abort()方法用于取消请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button type="button">点我</button>
</body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script>
   let btn =  document.querySelector('button')
   btn.addEventListener('click',function(){
       let xhr = new XMLHttpRequest();
       xhr.open("GET", 'http://localhost:3000/?age="19"');
       xhr.send();
       xhr.onload=function(){
           console.log(xhr.responseText)
       }
       //xhr.abort()方法用于取消请求
       setTimeout(() => xhr.abort(), 2000);  
   })
</script>
</html>

第三部分:请求地址(node部分)

// 导入三方插件
const express = require('express')
// 第二步:调用express()
const app = express()
// 设置对应的请求处理函数
app.get('/',(req,res)=>{
    //获取请求过来的数据req.qyery 
    console.log(req.query)
    // res响应出去的数据
    res.setHeader("Access-Control-Allow-Origin", "*")
    setTimeout(()=>{
        res.send({name:"张三"})
    },3000)
})
 app.listen(3000,()=>{
    console.log('开始监听3000',3000)
 })

猜你喜欢

转载自blog.csdn.net/m0_62823653/article/details/125731366