当我从客户端(React JS)使用axios向服务器(spring)发出post请求时,服务器的响应时间超过2分钟。因此,当需要 2 分钟以上时,客户端不会等待接收响应。所以我尝试使用下面的代码片段覆盖默认超时。但它不起作用。请帮助我解决问题。
const httpClient = Axios.create();
httpClient.defaults.timeout = 240000;
return httpClient.post(url, data).then(
res => res
).catch(err => err);
如果您查看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
覆盖默认值或将其作为选项传递给您的调用。
您还可以在文档中看到另一个示例。
如果它不起作用,可能您的 axios 版本已过时,或者您缺少某些内容。
创建 axios 实例时,该实例将应用于所有 api 调用
const httpClient = Axios.create({ timeout: 2 * 60 * 1000 });
您可以在api调用中传递
timeout
参数
httpClient.post(url, data, { timeout: 2 * 60 * 1000 })
如果您处于
nodejs17.3+
,实现此目的的最简单方法如下。
await axios({
method: 'post',
url: url,
headers: headers,
data: payload,
signal: AbortSignal.timeout(2 * 60 * 1000), // this will handle connection timeout. After waiting for 2 minutes an exception will be thrown
timeout: 2 * 60 * 1000 // This one handles ONLY response timeout
})
请注意,您必须分别处理连接超时和响应超时。
参考:官方文档