简体   繁体   English

如何检查服务器是否可以在react-native中访问

[英]How to check if server is reachable in react-native

I want to check if the server my app is trying reach is reachable (When internet is reachable) before making a request. 我想在发出请求之前检查我的应用程序正在尝试访问的服务器是否可访问(当可以访问互联网时)。

I am using Fetch API and right now I am using function timeout which works well but my question is is there any way by which I can check if server is reachable. 我正在使用Fetch API,现在我正在使用功能超时,但是我的问题是有什么方法可以检查服务器是否可以访问。

I tried using all-reacheable npm package and added following code but I do not get any call back response. 我尝试使用all-reacheable npm包并添加了以下代码,但我没有得到任何回调响应。

isReachable([
    'http://aposddasd.com',
    'http://google.com'
], (err, reachable, host) => {
  console.log('Server is' + reachable); //=> false
  console.log('App log' +  host); //=> 'http://aposddasd.com'
});

Can you help me with what is best way to achieve this? 你能帮助我找到最好的方法吗?

You can use a Promise.race() which will return the first promise to resolve or reject - they're pretty awesome actually! 您可以使用Promise.race() ,它将返回解决或拒绝的第一个承诺 - 实际上它们非常棒! Checkout the docs here: 在这里查看文档:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/race https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/race

Here's a simple function which times out after 3ms - it's using httpbin to simulate a delay of 5s: 这是一个简单的函数,在3ms后超时 - 它使用httpbin来模拟5s的延迟:

const isAvailable = () => {
    const timeout = new Promise((resolve, reject) => {
        setTimeout(reject, 300, 'Request timed out');
    });

    const request = fetch('https://httpbin.org/delay/5');

    return Promise
        .race([timeout, request])
        .then(response => alert('It worked :)'))
        .catch(error => alert('It timed out :('));
}

isAvailable();

Checkout the fiddle here: https://jsfiddle.net/edcs/8Lcg8a8j/10/ 在这里查看小提琴: https//jsfiddle.net/edcs/8Lcg8a8j/10/

I'm afraid if there is any function for that. 我担心是否有任何功能。 But you can put the Fetch API inside a javascript setTimeout() and give it for example 20 seconds. 但是你可以将Fetch API放在一个javascript setTimeout()中,例如20秒。 if you don't get results by 20 seconds, probably server is not reachable. 如果你没有得到20秒的结果,可能无法访问服务器。

setTimeout({ this.FetchData(); }, 20000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM