首页 > 其他分享 >interceptors 请求拦截器

interceptors 请求拦截器

时间:2022-11-20 22:55:59浏览次数:39  
标签:animation axios return 请求 interceptors token 拦截器 webkit response

需求:发送请求前拦截,显示加载页面,响应结束后隐藏加载页面。

一、定义加载页面,在该界面添加一个控制显示与隐藏的命令 v-show。

<div>
  <div class="spinner" v-show='isShow'>
    <div class="rect1"></div>
    <div class="rect2"></div>
    <div class="rect3"></div>
    <div class="rect4"></div>
    <div class="rect5"></div>
  </div>
  <button @click='sendAjax'>发请求</button>
</div>

二、在 sendAjax 方法中实现一个 cookie 的机制。

1、添加请求拦截器 interceptors.request 。

// 添加请求拦截器
this.$axios.interceptors.request.use((config)=>{
// 在发送请求之前做什么
var token = localStorage.getItem('token');
if(token){
  // 配置对象设置响应头
  config.headers['token'] = token;
}
this.isShow = true;
return config;
},function(error){
  // 对请求错误做些什么
  return Promise.reject(error);
});

2、添加响应拦截器 interceptors.response 。

// 添加响应拦截器
this.$axios.interceptors.response.use((response)=>{
// 对响应数据做点什么
console.log("这是响应"+response.data.token);
if(response.data.token){
  localStorage.setItem('token', response.data.token);
}
// 响应结束
this.isShow = false;
return response;
},(error)=>{
  // 对响应错误做点什么
  return Promise.reject(error);
});

3、发送请求。

this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/';
this.$axios.get('')
.then(res=>{
  console.log(res);
})
.catch(err=>{
  console.log(err);
})

 

完整代码如下:

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">
    .spinner {
        margin: 100px auto;
        width: 50px;
        height: 60px;
        text-align: center;
        font-size: 10px;
    }
    .spinner>div {
        background-color: #67CF22;
        height: 100%;
        width: 6px;
        display: inline-block;
        -webkit-animation: stretchdelay 1.2s infinite ease-in-out;
        animation: stretchdelay 1.2s infinite ease-in-out;
    }
    .spinner .rect2 {
        -webkit-animation-delay: -1.1s;
        animation-delay: -1.1s;
    }
    .spinner .rect3 {
        -webkit-animation-delay: -1.0s;
        animation-delay: -1.0s;
    }
    .spinner .rect4 {
        -webkit-animation-delay: -0.9s;
        animation-delay: -0.9s;
    }
    .spinner .rect5 {
        -webkit-animation-delay: -0.8s;
        animation-delay: -0.8s;
    }
    @-webkit-keyframes stretchdelay {
        0%,
        40%,
        100% {
            -webkit-transform: scaleY(0.4)
        }
        20% {
            -webkit-transform: scaleY(1.0)
        }
    }
    @keyframes stretchdelay {
        0%,
        40%,
        100% {
            transform: scaleY(0.4);
            -webkit-transform: scaleY(0.4);
        }
        20% {
            transform: scaleY(1.0);
            -webkit-transform: scaleY(1.0);
        }
    }
    </style>
</head>
<body>
    <div id="app">
    </div>
    <script type="text/javascript" src="../vue/vue.js"></script>
    <script type="text/javascript" src="node_modules/axios/dist/axios.js"></script>
    <script type="text/javascript">
        var App = {
            data(){
                return{
                    isShow:false
                }
            },
            template:` 
                <div>
                    <div class="spinner" v-show='isShow'>
                        <div class="rect1"></div>
                        <div class="rect2"></div>
                        <div class="rect3"></div>
                        <div class="rect4"></div>
                        <div class="rect5"></div>
                    </div>
                    <button @click='sendAjax'>发请求</button>
                </div>
            `,
            methods:{
                sendAjax(){
                    // 实现一个类似cookie的机制
                    // 添加请求拦截器
                    this.$axios.interceptors.request.use((config)=>{
                        // 在发送请求之前做什么
                        var token = localStorage.getItem('token');
                        if(token){
                            // 配置对象设置响应头
                            config.headers['token'] = token;
                        }
                        this.isShow = true;
                        return config;
                    },function(error){
                        // 对请求错误做些什么
                        return Promise.reject(error);
                    });
                    // 添加响应拦截器
                    this.$axios.interceptors.response.use((response)=>{
                        // 对响应数据做点什么
                        console.log("这是响应"+response.data.token);
                        if(response.data.token){
                            localStorage.setItem('token', response.data.token);
                        }
                        // 响应结束
                        this.isShow = false;
                        return response;
                    },(error)=>{
                        // 对响应错误做点什么
                        return Promise.reject(error);
                    });
                    this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/';
                    this.$axios.get('')
                    .then(res=>{
                        console.log(res);
                    })
                    .catch(err=>{
                        console.log(err);
                    })
                }
            }
        }
        // 将axios挂载到Vue对象上
        Vue.prototype.$axios = axios
        new Vue({
            el:'#app',
            template:` 
                <App/>
            `,
            components:{
                App
            }
        });
    </script>
</body>
</html>

 

标签:animation,axios,return,请求,interceptors,token,拦截器,webkit,response
From: https://www.cnblogs.com/sfwu/p/16909956.html

相关文章

  • 文件上传取消请求
    通过请求配置参数里面的 cancelToken可取消请求,通过CancelToken.source工厂方法创建一个canceltoken。需求:在文件上传的基础上,加入取消请求和继续上传功能。一、改造......
  • Token和axios拦截器的初步了解和使用
    token为什么要有token默认情况下,HTTP是一个无状态协议,也就是说任何客户端浏览器都可以访问服务器,但是服务器并不能知道浏览器到底是属于哪个用户的。当客户端多次向服务......
  • SpringMVC - 获取请求参数,作用域
    一、获取请求参数1.原生serveltAPI@ControllerpublicclassTestController{@RequestMapping("/test01")publicStringtest01(HttpServletRequestrequest){......
  • 需要授权的 API ,必须在请求头中使用 Authorization 字段提供 token 令牌
    原文链接:https://blog.csdn.net/wanghuohuo1998/article/details/118087204需要授权的 API ,必须在请求头中使用添加字段需要授权的API,必须在请求头中使用 Authoriz......
  • 页面卸载前(用户关闭页面)向服务器发送请求
    废话不说,直接进正题。最近项目有个需求需要在用户关闭页面时将页面存留的统计数据发送到后端。该需求有两个关键点:监听页面卸载在卸载时发送数据如何监听用户关闭页......
  • Http2Bean——基于OkHttp与Gson的网络请求工具
    publicclassHttp2Bean<T>{privatefinalOkHttpClientclient=newOkHttpClient();privatefinalClass<T>clazz;privatefinalRequest.Builderreq......
  • ASP.NET Core教程-Pipeline(请求管道)
    更新记录转载请注明出处:2022年11月20日发布。2022年11月16日从笔记迁移到博客。请求管道是什么类似于水的管道,有流进流出。在ASP.NETCore中Server进行监听用户的......
  • 第4章SpringMVC核心技术-一个或者多个拦截器拦截器,
    第4章SpringMVC核心技术.拦截器拦截器SpringMVC中的Interceptor拦截器是非常重要和相当有用的,它的主要作用是拦截指定Java框架SpringMVC5的用户请求,并进行相应的预......
  • 关于GET/POST请求传输时URL编码的介绍记录随笔
    UTF-8编码的汉字:少数是汉字每个占用3个字节,多数占用4个字节#GET请求编码Chrome会先把URL中非ASCII字符按照某种编码格式(谷歌浏览器是UTF-8)编码成byte数组后,然后转成16进......
  • SpringMVC-拦截器
    一、拦截器SpringMVC提供了拦截器在处理请求之前,之后,渲染视图后执行逻辑处理。接口是HandlerInterceptor。preHandle方法在处理请求之前执行,postHandle方法是在处理请求后......