最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if the API is reachable - Stack Overflow

programmeradmin6浏览0评论

What is the best way to tell if the API is online? I know I can check if the user has the Internet connection using navigator.onLine but how about the API?

Should I send a request to some simple endpoint and see if the data goes back to me?

What is the best way to tell if the API is online? I know I can check if the user has the Internet connection using navigator.onLine but how about the API?

Should I send a request to some simple endpoint and see if the data goes back to me?

Share Improve this question asked Aug 9, 2017 at 12:03 mdmbmdmb 5,2939 gold badges51 silver badges97 bronze badges 2
  • Absolutely. There is no other way that you can check it. Make a call and check the [status](w3/Protocols/rfc2616/rfc2616-sec10.html )of it. – Suresh Atta Commented Aug 9, 2017 at 12:07
  • Try to use an ajax request using GET method. A 404 status code is the best sign that the server has not found anything matching the URI given, which means the api is not reachable at least in that endpoint. – Bmaed Riasbet Commented Aug 9, 2017 at 12:11
Add a ment  | 

2 Answers 2

Reset to default 4

I would just simple do a simple "ping" type test, if your API was https://api.example./auth/user I would just do a simple GET request on https://api.example. if this returns the expected result you can assume the API is online. This isn't the best test because there still could be a problem with the API but the concept of it being on line is still checked.

If the service you are using has a status page 9/10 the API will be on there. You could use this page to your advantage by scraping the page and checking the status of the API. Say your using the Bitbucket API you could GET this page status.bitbucket and then check that the API state is OPERATIONAL.

Try this under try catch block and log error or do continue rest of the code based on that

try {
   //api request 
} catch (e)
   // log error
   // Set flag
}

Based on the flag, do you next action item

发布评论

评论列表(0)

  1. 暂无评论