使用拦截器延迟所有请求 [英] Delay all requests with interceptor
问题描述
出于调试目的,我想延迟所有请求,以便可以模拟加载资源实际上需要时间.我想这可以在拦截器中完成.
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.
这篇关于使用拦截器延迟所有请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!