处理预期和意外的 http 请求失败

Handling expected and unexpected http request failures

我正在使用 angularJSPHP.

构建一个 http 请求 <-> 响应 link

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

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

$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 状态问题相关的类似线程:。不幸的是,这无助于解决问题。

请求方法为OPTIONS时,只需要设置headers并退出

类似

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

此处的 CORS 方法可能会有所帮助