使用拦截器延迟所有请求

编程入门 行业动态 更新时间:2024-10-27 22:19:53
本文介绍了使用拦截器延迟所有请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

出于调试目的,我想延迟所有请求,以便可以模拟加载资源实际上需要时间.我想这可以在拦截器中完成.

For debugging purposes I want to delay all requests so that I can simulate that it actually takes time to load resources. I guess that this can be done in a interceptor somehow.

我确实设法通过以下方式延迟了单个请求:

I do manage to delay single requests now with:

const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)); delay(1000) .then(() => { axios.post( ... ).then((response) => { ... }); });

但是我会很乐意在一处处理所有请求.

But I would be more nice to do it for all requests at one place.

推荐答案

抱歉,回复晚了,但是我遇到了类似的问题.我想对几乎所有请求都使用人为延迟,以提高可用性和调试目的.我创建了一个新服务(位于src/services/HttpClient.js)并使用了全局请求拦截器:

Sorry for the late response, but I've had a similar issue. I'd like to use an artificial delay for almost all requests to improve usability and for debugging purposes too. I've created a new service (situated at src/services/HttpClient.js) and use a global request interceptor:

import axios from 'axios'; // Create a new instance. const service = axios.create({ baseURL: process.env.API_ENDPOINT, delayed: true // use this custom option to allow overrides }); service.interceptors.request.use((config) => if (config.delayed) { return new Promise(resolve => setTimeout(() => resolve(config), 600)); } return config; }); export default service;

自定义配置选项delayed可用于覆盖全局行为.以下请求将立即执行:

The custom config option delayed can be used to override the global behavior. The following request will be performed without a delay:

import $http from '@/services/HttpClient'; $http.get('/example-url', { delayed: false }).then((response) { … });

后台请求不会延迟我的应用程序.但是,由用户的操作触发的所有请求都使用延迟.

Requests in the background don't use a delay in my app. But all requests triggered by an action by the user use the delay.

更多推荐

使用拦截器延迟所有请求

本文发布于:2023-11-26 14:21:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634119.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:拦截器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!