【问题标题】:how to set axios timeout如何设置axios超时
【发布时间】:2021-06-28 05:42:13
【问题描述】:

javascript/react/node/axios 的新手。对编程并不陌生

在移动响应应用程序中工作的 axios 尝试超时时遇到问题。

我有一个 API 端点设置为测试的节点服务器;这将接受请求,抛出错误并且根本不响应。

例如:抛出新的错误(“测试超时”)

应用程序挂起并且不会继续运行,直到我停止执行 catch 块的节点服务器。

我可以通过让服务器在抛出错误之前执行 console.log("hello") 来验证应用程序是否与服务器建立了联系

我通过新文件夹“react-native init”创建了一个新的 react 应用,在 app.js 上创建了一个按钮来启动调用。相关代码:

const axios = require('axios')

const test1Press = async () => {

  console.log("test1 pressed")

  // obviously not the actual url in this stackoverflow post
  axios.defaults.baseURL = 'https://mynodeserver.com/api'

  console.log("pre call")

  try
  {
    await axios.post('/debug/throw', {timeout: 2000})
    console.log("post call passed")
  }
  catch (err)
  {
    console.log("post call failed")
  }
}

控制台窗口显示预调用;然后挂起。当我停止节点服务器时,应用程序立即记录“post call failed”

我也试过了:

axios.defaults.timeout = 2000

并使用 axios 实例,例如:

axinst = axios.create({
  baseURL: 'https://parcelscan-staging.ctilogistics.com/api',
  timeout: 2000
})

console.log("pre call")

try
{
  await axinst.post('/debug/throw')
  console.log("post call passed")
}
catch (err)
{
  console.log("post call failed")
}

我看不出我做错了什么。

编辑:

在进一步的研究中,我发现有类似问题的论坛帖子;截至 2020 年 5 月,看起来 axios 超时可能不可靠;一年后的现在是 2021 年 6 月?

建议的解决方案是取消令牌,例如:

const source = CancelToken.source();
try {
    let response = null;
    setTimeout(() => {
        if (response === null) {
            source.cancel();
        }
    }, 2000);
        
    response = await axios.post('/url',null,
        {cancelToken: source.token});
    // success
} catch (error) {
// fail
}

对此进行了测试并正常工作

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    使用await axios.post('/debug/throw', {timeout: 2000}),实际上您将有效负载发送 {timeout: 2000} 到服务器,而不是将超时设置为 2 秒。查看示例here

    我用 axios 的另一种语法进行了测试,它工作正常

    const test1Press = async () => {
    
        console.log("test1 pressed")
    
        // obviously not the actual url in this stackoverflow post
        axios.defaults.baseURL = 'http://localhost:9000'
    
        console.log("pre call")
        console.log(new Date().toUTCString());
        try {
            await axios({
                method: 'post',
                url: '/',
                timeout: 2000 // only wait for 2s
            })
            console.log(new Date().toUTCString());
            console.log("post call passed")
        }
        catch (err) {
            console.log(new Date().toUTCString());
            console.log("post call failed")
        }
    }
    
    test1Press();
    

    在服务器端,我等待 5 秒以在客户端出现超时错误

    const http = require('http');
    
    const server = http.createServer(function (req, res) {
        setTimeout(function () {
            res.write('Hello World!');
            res.end();
        }, 5 * 1 * 1000); // after 5s
    })
        .listen(9000);
    

    运行上面的代码会在 2 秒后出现超时错误

    test1 pressed
    pre call
    Mon, 28 Jun 2021 09:01:54 GMT
    Mon, 28 Jun 2021 09:01:56 GMT
    post call failed
    

    编辑 我测试了创建 axios 的实例,这给了我相同的结果:

    const test1Press = async () => {
    
        console.log("test1 pressed")
    
        // obviously not the actual url in this stackoverflow post
        const instance = axios.create({
            baseURL: 'http://localhost:9000',
            timeout: 2000,
        });
    
        console.log("pre call")
        console.log(new Date().toUTCString());
        try {
            await instance.post('/');
            console.log(new Date().toUTCString());
            console.log("post call passed")
        }
        catch (err) {
            console.log(new Date().toUTCString());
            console.log("post call failed")
        }
    }
    
    test1Press();
    

    【讨论】:

    • 您的第二个示例与我的上一个示例相同。我已经更改了我的服务器代码以匹配您的代码,因此它现在处于“休眠”状态而不是抛出错误.. 我的应用程序仍然等待 5 秒,并且我没有得到 2 秒失败的 catch 块 - 两个版本。嗯。我认为这不是语法问题;可能与与 axios/react/other 的某种冲突有关
    • 我正在使用 https - 即 myurl.com/api/debug/throw 的 URL 会导致 https 导致超时问题吗?
    • 我认为它与 https/http 无关。我没有用反应测试,可能是它的区别。可以只用 axios 做测试吗?
    • 这就是我在 react/javascript/axios 方面的有限经验发挥作用的地方 :( 我们致力于反应解决方案,但我可以用另一个包替换 axios;我可能会尝试
    • 这个链接确实表明 axios 可以很好地与 react 配合使用并支持超时..medium.com/enappd/…
    【解决方案2】:

    假设您通过 axios 请求了 URL,并且服务器需要很长时间才能响应,在这种情况下 axios 超时将起作用。

    但是您没有互联网连接,或者您请求的 IP 地址或域名不存在,在这种情况下 axios 超时将不起作用。

    See original answer for solution

    【讨论】:

    • 链接是一个不同的问题。我可以验证是否建立了连接。所以互联网连接/IP地址/域名都可以;我已经让服务器记录了一个请求。所以在这种情况下,axios 超时应该可以工作,但它不是
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2011-08-09
    • 2011-06-23
    • 2013-10-26
    • 2011-11-08
    • 1970-01-01
    相关资源
    最近更新 更多