dongshan9619 2018-05-22 03:48
浏览 174
已采纳

php - 返回错误,以便js承诺捕获

Is that even possible to return some kind of error (ie using header()) from php file that is received by ajax call and reveived as error (via catch method?)

consider such a php (example doesnt work correctly):

<?php 

session_start();

$_SESSION['user_id'] = 1;

 header("Access-Control-Allow-Origin: *");
 header("Access-Control-Allow-Credentials: true");
 header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT");
 header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");



if ( $_SESSION['user_id'] == 0 ) {
        header('Content-Type: application/json');
        print json_encode(["test" => 123]);
    }
else
    {
       header('HTTP/1.1 1337 Internal Server Kalreg');
       header('Content-Type: application/json; charset=UTF-8');
        die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
}
?>

and js:

axios.get('loginStatus.php', { crossDomain: true })
        .then(function (response) {
        console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });


    }
  }

Now because $_SESSION['user_id'] is set to 1 server error is generated, and because of that catch in js should react in proper way. In fact it is not - in chrome-dev-tools i get an error:

xhr.js?ec6c:178 OPTIONS http://192.168.0.15/game/src/server/loginStatus.php 500 (Internal Server Error) Failed to load http://192.168.0.15/game/src/server/loginStatus.php: Response for preflight has invalid HTTP status code 500.

Is that possible? Or should i return just JSON file with error or not and manage it with .then not .catch?

Kalreg.

展开全部

  • 写回答

1条回答 默认 最新

  • dongxiezhuo8852 2018-05-22 04:24
    关注

    If you want catch to be executed and this is decided on server-side, then you will need to set an unsuccessful status code via http_response_code. A status code of 417 (Expectation failed) seems to be a good pick in your case, but you can see here what you can pick from.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部