javascript - 需要覆盖axios post请求的默认超时时间

标签 javascript reactjs axios timeout settimeout

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

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

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

最佳答案

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

有两种设置超时的方法。

// 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 版本已过时,或者您缺少某些内容。

关于javascript - 需要覆盖axios post请求的默认超时时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59987087/

相关文章:

javascript - Reactjs将本地的csv文件转换为json

javascript - Axios 返回未决 promise

javascript - 脚本在 Chrome 中运行但不在 firefox 中运行

javascript - 为什么 Array.prototype.sort 将未定义的值放在最后?

javascript - jquery 日期格式,每个浏览器都不同?

javascript - 用于 token 刷新的 Axios 全局拦截器

javascript - 你如何让axios GET请求等待?

javascript - AngularJS:如何从 Controller 调用指令范围内定义的函数?

reactjs - 为什么将观察者添加到 react-query 会导致它忽略其 `enabled` 属性?

node.js - Express Multer 在上传前验证字段