dongshan9619 2018-05-22 11: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 12: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.

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

报告相同问题?

悬赏问题

  • ¥15 求会做聚类,TCN的朋友有偿线上指导。以下是目前遇到的问题
  • ¥100 无网格伽辽金方法研究裂纹扩展的程序
  • ¥15 错误于library(org.Hs.eg.db): 不存在叫‘org.Hs.eg.db’这个名称的程序包,如何解决?
  • ¥60 求一个图片处理程序,要求将图像大小跟现实生活中的大小按比例联系起来的
  • ¥50 求一位精通京东相关开发的专家
  • ¥100 求懂行的大ge给小di解答下!
  • ¥15 pcl运行在qt msvc2019环境运行效率低于visual studio 2019
  • ¥15 MAUI,Zxing扫码,华为手机没反应。可提高悬赏
  • ¥15 python运行报错 ModuleNotFoundError: No module named 'torch'
  • ¥100 华为手机私有App后台保活