处理不可用的页面 (statusCode)

Handle an unavailable page (statusCode)

我目前正在使用以下代码检查当前页面的状态代码:

$.ajax({
type: 'HEAD',
url: window.location.href,
success: function() {
  console.log("Ok");
},    
error: function() {
  console.log("error");
}
});

如果响应代码在 200 - 299 之间,则页面存在;如果响应代码在 400 - 499 之间,则页面不存在。

但例如 405 错误对我来说并不是真正的错误,页面显示良好,因此没有理由处于错误状态。

所以我添加了另一个测试:

error: function(jqXHR, textStatus, errorThrown) {
  console.log('jqHRX : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus + ' errorThrown : ' + errorThrown);
  if (errorThrown != "OK") //or jqHRX.statusText
    console.log("error");
}

例如,如果我浏览到 returns 一个 405 代码的页面,我将得到以下输出: jqHRX : {"readyState":4,"responseText":"","status":405,"statusText":"OK"} textStatus : error errorThrown : OK

如果是 404 错误: jqHRX : {"readyState":4,"responseText":"","status":404,"statusText":"Not Found"} textStatus : error errorThrown : Not Found error

  1. 那么,errorThrown 等于 "OK" 的所有页面当前都可用吗?我偶然发现了405的例子..我真的不知道它是否是一个孤立的案例。
  2. 有没有更好的方法来处理这个问题?

谢谢!

亚历克斯

编辑:例如,https://developer.chrome.com/home returns 405 与我的代码,但在我的应用程序中没有必要将此视为错误。

奇怪,你可以用http://tools.seobook.com/server-header-checker/验证statusCode:结果是405 但是如果你检查 http://httpstatus.io/ 结果是 200

来自 jQuery 文档:

"When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

依靠这个并不是最佳的,因为服务器可以为您提供他们认为正确的任何状态文本。所以我基本上可以给你发一个 500 页,errorThrown 是 "I know foo better than bar".

此外,带有 405 的页面绝对不应 "display well",因为此错误意味着此页面上不允许使用 HTTP 方法。通常在您尝试获取仅用于 POST、PUT、PATCH 的端点时看到。

如果您有非标准错误处理(您不认为 405 之类的错误是应用程序内部的错误),请使用响应状态代码而不是其他任何内容。您还可以考虑使用 jQuery.ajax().complete() 在一处同时处理成功和错误。

tl;dr :使用 GET 而不是 HEAD 将起作用。 Get实际上是抛出405错误的不允许的方法。

回答: 感谢我的一位同事,它向我展示了 Postman。

它允许我通过 GET、PUT、POST、HEAD、LOCK 等不同的方法检查页面的状态代码。似乎对于一堆网站 (chrome 开发人员文档、亚马逊等)HEAD 返回 405 而 GET 返回 200

根据w3.org

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.

所以就我而言,有时我发现网站不允许 HEAD 请求。

通过替换代码解决:

$.ajax({
 type: 'GET',
 url: window.location.href,
 error: function() {
     console.log("error");
 }
});