【问题标题】:Need to override the default time out of Axios post request需要覆盖axios post请求的默认超时时间
【发布时间】:2022-01-14 17:35:39
【问题描述】:

当我使用 axios 从客户端(React JS)向服务器(spring)发出 post 请求时,服务器的响应时间超过 2 分钟。因此,当需要更多 tan 2 分钟时,客户端不会等待接收响应。所以我尝试用下面的代码 sn-p 覆盖默认超时。但它不起作用。请帮助我解决问题。

const httpClient = Axios.create();
httpClient.defaults.timeout = 240000;

return httpClient.post(url, data).then(
 res => res
).catch(err => err);

【问题讨论】:

标签: javascript reactjs axios timeout settimeout


【解决方案1】:

如果您查看docs(这是另一个主题,但显示了超时示例)。

有两种设置timeout的方法。

// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});

您可以使用 instance.defaults.timeout 覆盖默认值,或将其作为选项传递给您的调用。

您还可以看到另一个example in the docs

如果它不起作用,可能是你的 axios 版本过时,或者你遗漏了一些东西。

【讨论】:

    【解决方案2】:

    将应用于所有api调用的axios实例的创建时间

    const httpClient = Axios.create({ timeout: 2 * 60 * 1000 });
    

    可以在api调用中传递timeout参数

    httpClient.post(url, data, { timeout: 2 * 60 * 1000 })
    

    【讨论】:

    • 这种方法在不到 2 分钟的超时时间内工作正常。当我尝试超时 3 分钟时,它会抛出错误为“无法加载响应数据”。
    • 而且我们无法捕获超时的响应,得到响应为“无法加载响应数据”
    • 当出现超时错误时,响应为空,什么都没有,
    猜你喜欢
    • 1970-01-01
    • 2013-02-17
    • 2019-02-21
    • 2014-07-18
    • 2019-11-11
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    相关资源
    最近更新 更多