firefox addon-sdk:处理http请求超时 [英] firefox addon-sdk : handle http request timeout

查看:164
本文介绍了firefox addon-sdk:处理http请求超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用附加sdk构建了一个Firefox附加组件。我需要做一个HTTP请求到一个特定的页面,我想处理连接超时,但在api中找不到任何东西: https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/request.html

我实际上看到的是客户端无法连接到服务器时的回调。

有没有办法达到这个目的?

SDK请求将始终调用 onComplete ,当请求被认为是为网络完成时。这意味着在任何情况下都会调用 onComplete ,无论请求是返回错误还是成功。



为了检测你得到的错误,你需要检查Response对象(传递给 onComplete 函数的对象)属性状态 response.status )。它包含请求的状态码。要查看状态代码,请考虑mozilla开发人员网络上的列表。如果响应状态为0,则请求完全失败,并且用户可能处于脱机状态,或者目标无法到达。



超时值可能是状态代码504或0.实现将类似于这样:
$ b

  var Request = require( SDK /请求); 
$ b $请求({
url:http://foo.bar/request.target,
onComplete:function(response){
if(response。状态== 0 || response.status == 504){
//连接超时处理
}
//可能检查其他状态代码
else {
//假设请求顺利


})。get();

我个人对请求对象使用了一个验证函数,已经得到了正确的回应,来自网络服务器的错误或连接问题(4xx和0状态码)。

I'm building a firefox add-on using the add-on sdk. I need to make a http request to a certain page and I want to handle the connection timeout but couldn't find anything in the api: https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/request.html

What I'm actually looking is a callback in case the client couldn't connect to the server.

Is there a way to achieve this?

解决方案

The SDK request will always call onComplete, when the request is considered done for the network. This means that onComplete is called in any case, disregarding if the request returned an error or a success.

In order to detect which error you've got, you need to check the Response object's (the object passed to the onComplete function) property "status" (response.status). It holds the status code for the request. To look up status codes, consider the list on the mozilla developer network. If the response status is 0, the request has failed completely and the user is probably offline, or the target couldn't be reached.

A timeout would either be a status code 504 or 0. The implementation would be similar to this:

var Request = require("sdk/request");

Request({
  url: "http://foo.bar/request.target",
  onComplete: function(response) {
    if(response.status==0||response.status==504) {
      // do connection timeout handling
    }
    // probably check for other status codes
    else {
      // assume the request went well
    }
  }
}).get();

I personally use a validation function on the request object, which returns me a number which depends whether I've got a correct response, an error from the web server or a connection issue (4xx and 0 status codes).

这篇关于firefox addon-sdk:处理http请求超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆