【问题标题】:Handling expected and unexpected http request failures处理预期和意外的 http 请求失败
【发布时间】:2016-06-12 22:17:07
【问题描述】:

我正在使用angularJSPHP 构建一个http 请求 响应链接。

  • 在服务器端有一个PHP 服务。
  • 在客户端有一个JS (angularJS) 服务。

当我只是发送和接收数据时,代码工作正常。但是现在我想处理服务器出现问题的情况。也就是说,我想从服务器返回出错的状态码,甚至是自定义错误消息。

这是我用来发送数据的代码:

$http({
    method: 'POST',
    url: 'http://' + remoteIP + ':1234/test/getCM2.php',
    dataType: 'json',
    data: { test: 'abc'},
    headers: { 'Content-Type': 'application/json; charset=UTF-8' }
}).success(function (data, status, headers, config) {
    if (typeof data === 'object') {
        return data;
    } else {
        return $q.reject(data);
    }
}).error(function (data, status, headers, config) {
    return $q.reject(data);
});

数据作为JSON 对象发送。在服务器端,我处理数据:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: origin, content-type, accept, authorization");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD");
header('Content-Type: application/json');

$postdata = file_get_contents("php://input");
$request = json_decode($postdata, true);
$test = $request['test'];

if (empty($test)) {
    // what to do here????
    // bad code ahead:
    http_response_code(401);
}

try {

    echo json_encode([
        "outData" => "def"
    ]);
} catch(Exception $e) {
    // what to do here????
    // bad code ahead:
    $output = [
        'error'   => $e->getMessage()
    ];
    echo(json_encode($output));
}

?>

PHP 我正在尝试将HTTP 响应状态设置为如下:

http_response_code(401);

当我在Chrome 调试器中检查响应时,它可以完美运行:

但在angularjs 中,我得到的只是状态=-1

通常在发送正确的JSON 请求(未设置http_response_code(401);)时,会发出2 个请求,首先是OPTION,然后是POST:

所以,看起来OPTION 请求一开始就接收了我的HTTP 401 错误消息,但angularJS 从未看到此错误消息,因为它只是在寻找POST 响应。所以我看到的状态是-1,而不是401POST 甚至都没有。

我需要用错误消息回复客户,但我需要一个错误,它意味着什么,而不是 -1。处理这种情况最合适的方法是什么?

-1 状态问题相关的类似线程:stackoverflow。不幸的是,这无助于解决问题。

【问题讨论】:

  • 从 .error 块打印状态
  • Options 是允许跨域请求的飞行前检查。您的 API 应该拦截这些并返回 200 以获得有效的主机名,或者返回错误。

标签: javascript php angularjs http-status-code-404


【解决方案1】:

只需要在请求方式为OPTIONS时设置headers并退出即可。

类似

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
     exit;
}
// only enter this part for POST
$postdata = file_get_contents("php://input");

这里的 CORS 方法可能会有所帮助 https://stackoverflow.com/a/9866124/1175966

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 2016-05-24
    • 2015-12-04
    • 1970-01-01
    相关资源
    最近更新 更多