2016-02-29 328 views
0

我正在構建http請求< - >使用angularJSPHP的響應鏈接。處理預期的和意外的http請求失敗

  • 在服務器端有PHP服務。
  • 在客戶端有一個JSangularJS)服務。

當我只是發送和接收數據時,代碼工作正常。但是現在我想處理服務器出現問題時的情況。也就是說,我想從服務器返回狀態代碼,發現錯誤或甚至是自定義錯誤消息。

這裏是我使用發送數據的代碼:

$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調試檢查rsponse:

enter image description here

但在angularjs我得到的只是狀態= -1

enter image description here

通常發送正確JSON請求時(不設置http_response_code(401);),還有正在取得2個請求,第一個選項,然後POST:

enter image description here

所以,它看起來像OPTION請求在開始時會出現我的HTTP 401錯誤消息,但angularJS從不會看到此錯誤消息,因爲它僅查找POST respo NSE。所以我看到的狀態是-1,而不是401POST甚至沒有製造。

我需要回復客戶端的錯誤消息,但我需要一個錯誤,這意味着什麼,而不是-1。處理這種情況最適合的方式是什麼?

-1狀態問題類似的線程:stackoverflow。不幸的是,它並沒有幫助解決這個問題。

+0

打印狀態從.error阻止 –

+0

選項是允許跨域請求飛行前檢查。你的API應該攔截那些並返回200作爲有效的主機名,或者返回一個錯誤。 –

回答

1

您只需設置標題並在請求方法爲OPTIONS時退出。

喜歡的東西

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