401响应不返回json

时间:2015-07-29 17:57:17

标签: javascript php json http-headers phalcon

这是我使用phalcon的api:

$response = new Response();
$response->setStatusCode( 401, 'Unauthorized' );
$response->setContentType( 'application/json', 'UTF-8' );
$response->setJsonContent( ['status' => 401] );
$response->setHeader('Access-Control-Allow-Origin',  '*');
$response->setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Authorization');
$response->setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
return $response;

这是我使用Mithril框架的请求:

options = {method: 'GET', url: "http://.../flights/recent"};
var oldConfig = options.config || function() {};

options.config = function(xhr) {
    xhr.setRequestHeader("Authorization", "Bearer " + AuthComponent.token());
    oldConfig(xhr);
};

var deferred = m.deferred();

m.request(options).then(deferred.resolve, function(error) {
    if(error.status === 401) {
        AuthComponent.originalRoute = m.route();
        m.route('/login');
    }
});

return deferred.promise;

api代码显然只是一个测试,而不是最终的代码。它应该模拟一个过期的令牌,它响应具有401头和json status=401的请求,因此可以在JS error.status中读取它。

m.request知道这是一个错误,但error变量返回null

在Google Chrome开发人员工具上,请求显示401 Unauthorized但响应标签显示“此请求没有可用的响应数据。”。

1 个答案:

答案 0 :(得分:0)

您忘记了send()回复。

$response = new \Phalcon\Http\Response();
$response->setStatusCode( 401, 'Unauthorized' );
$response->setContentType( 'application/json', 'UTF-8' );
$response->setJsonContent( ['status' => 401] );
$response->send();

您应该查看本教程:https://docs.phalconphp.com/pt/latest/reference/tutorial-rest.html