Axios:如何设置请求超时

在 Axios 中,默认超时为 0。这篇快速而直接的文章向您展示了在使用 Axios 发出 HTTP 请求时设置自定义超时的几种方法。

为单个请求设置超时

您可以为单个请求设置超时,如下所示:

try {
      const response = await axios('https://www.kindacode.com', {
        timeout: 5000, // Override the default timeout to 5 seconds
        method: 'GET',
      });
      console.log(response);
} catch (err) {
      console.log(err);
}

或者像这样:

try {
      const response = await axios.post(
        'https://jsonplaceholder.typicode.com/posts',
        {
          title: 'foo',
          body: 'bar',
        },
        {
          timeout: 5000, // Override the default timeout for this request
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

      console.log(response.data);
} catch (error) {
      console.log(error);
}

为多个请求设置超时

您可以通过初始化一个 Axios 实例来为多个请求设置超时。这是一个例子:

// Create an axios instance
// and set the timeout for this instance
const client = axios.create({
      baseURL: 'https://jsonplaceholder.typicode.com',
      timeout: 3000, // 3 seconds
});

// make a GET request
try {
      const response = await client.get('/posts');
      console.log(response.data);
} catch (error) {
      console.log(error);
}

// make a POST request
try {
      const response = await client.post('/posts', {
        title: 'foo',
        body: 'bar',
        userId: 1,
      });
      console.log(response.data);
} catch (error) {
      console.log(error);
}