如何在 Slim Framework 中设置自定义响应状态码

How to set custom response status code in Slim Framework

我在我的新项目中使用 Angular JS、PHP 和 Slimframework。

我在 Angular JS 中使用了 promises 但如你所知,如果来自 API 的响应状态代码 return 为 200,则只有 "success" 部分有效。

在 Slimframework 中,默认响应状态代码是 200,而我所有的请求 return 状态代码都是 200。(如果没有错误是正常的)

但我想做一些验证,如果验证失败,我只想在 Slim 框架中更改或设置自定义状态代码。在这种情况下,我将能够使用 "error" 代码块

在 Angular JS 中发现问题

例如:

SlimFramework 部分

$app->get('/getUserInformations/{user_id}', function(Request $request, Response $response){

    if(isLoggedIn()){

        //Do something and send an answer with status code 200

    }else{

        //Send some errors with status code 500 or something else

    }

});

Angular JS部分:

user.getUserInformations = function(){
    var defer = $q.defer();

    $http.get($rootScope.defaultApiPath + '/getUserInformations/1')
        .success(function(response){

            //if status code is 200 this means user logged in. Do something

            defer.resolve(response);
        })
        .error(function(error, status){

            // if status code is 500 this means not logged in. Show error message

            defer.reject(error);
        });

    return defer.promise;
};

在 SlimFramework 的文档中我发现了类似

的内容
$newResponse = $response->withStatus(302);

$data = array('name' => 'Rob', 'age' => 40);
$newResponse = $oldResponse->withJson($data, 201);

但我无法使用它们。给我一些错误,找不到方法..

很快,我的问题是,如何在 slim 框架中设置自定义状态代码。

提前致谢

您正在寻找的答案是...

return $response->withStatus(xxx);

http://www.slimframework.com/docs/objects/response.html#the-response-status