需要覆盖 Axios post 请求的默认超时时间

Niv*_*sri 2 javascript timeout settimeout reactjs axios

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

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

return httpClient.post(url, data).then(
 res => res
).catch(err => err);
Run Code Online (Sandbox Code Playgroud)

Ven*_*sky 5

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

有两种设置方法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
});
Run Code Online (Sandbox Code Playgroud)

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

您还可以在 docs 中看到另一个示例

如果它不起作用,则可能是您使用的 axios 版本已过时,或者您遗漏了某些东西。


Zoh*_*jaz 1

当创建 axios 实例时,该实例将应用于所有 api 调用

const httpClient = Axios.create({ timeout: 2 * 60 * 1000 });
Run Code Online (Sandbox Code Playgroud)

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

httpClient.post(url, data, { timeout: 2 * 60 * 1000 })
Run Code Online (Sandbox Code Playgroud)