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

bfnvny8b  于 2022-12-10  发布在  Angular
关注(0)|答案(1)|浏览(181)

I am building an HTTP request <-> response link using AngularJS and PHP.

  • On the server side there is a PHP service.
  • On a client side there is a JS (AngularJS) service.

The code is working fine when I am just sending and receiving data. But now I want to handle situations when something goes wrong on the server. That is to say, I want to return status code from server that something went wrong or even a custom error message.
Here is the code which I am using to send data:

$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);
});

The data is sent as an JSON object. On server side I handle the data:

<?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));
}

?>

In PHP I am trying to set HTTP response status as following:

http_response_code(401);

It works flawlessly when I check the response in Chrome debugger:

But in AngularJS all I get is status = -1 :

Usually when sending correct JSON request (without setting http_response_code(401) ), there are 2 requests being made, first OPTION and then POST :

So, it seems like the OPTION request is taking my HTTP 401 error message at the beginning, but AngularJS never sees this error message because it is solely looking for the POST response. So the status which I see is -1 , not 401 . POST wasn't even made.
I need to reply to clients with an error message, but I need an error which means something, not a -1 . What would be the most appropriate way of handling such a situation?
I found a similar thread related to -1 status issue; unfortunately it doesn't help to solve the situation.

v1l68za4

v1l68za41#

You need to only set headers and exit when the request method is OPTIONS.
Something like

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

The CORS approach here might help https://stackoverflow.com/a/9866124/1175966

相关问题