【发布时间】:2018-11-01 04:15:20
【问题描述】:
是否有可能从 ajax 调用接收并作为错误接收的 php 文件返回某种错误(即使用 header())(通过 catch 方法?)
考虑这样一个php(例子不能正常工作):
<?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)));
}
?>
和js:
axios.get('loginStatus.php', { crossDomain: true })
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
现在因为 $_SESSION['user_id'] 设置为 1 会生成服务器错误,因此 js 中的 catch 应该以正确的方式做出反应。事实上它不是 - 在 chrome-dev-tools 我得到一个错误:
xhr.js?ec6c:178 选项 http://192.168.0.15/game/src/server/loginStatus.php 500(内部 服务器错误)加载失败 http://192.168.0.15/game/src/server/loginStatus.php: 回复 预检具有无效的 HTTP 状态代码 500。
这可能吗?或者我应该只返回有错误的 JSON 文件并使用 .then 而不是 .catch 来管理它?
卡雷格。
【问题讨论】:
标签: javascript php ajax promise