【问题标题】:401 response doesn't return json401 响应不返回 json
【发布时间】:2015-07-29 17:57:16
【问题描述】:

这是我使用 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 但响应选项卡显示“此请求没有可用的响应数据。”。

【问题讨论】:

    标签: javascript php json http-headers phalcon


    【解决方案1】:

    你忘记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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多