Delay all requests with interceptor

本小妞迷上赌 提交于 2020-08-26 07:18:48

问题


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.


回答1:


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;

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.



来源:https://stackoverflow.com/questions/47202661/delay-all-requests-with-interceptor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!